繁体   English   中英

单击按钮时隐藏JFrame而不停止程序

[英]Hiding JFrame when button is clicked without stopping program

我有一个jframe作为程序的一部分,用户可以通过按添加按钮来填充arraylist。 当他们完成数组列表的填充后,我希望他们在程序继续运行时单击完成按钮以隐藏jframe。

有没有办法做到这一点。 最初我使用的是System.exit(0),但这似乎终止了该程序。

public class Street extends JFrame {
    private static final Random randomNumbers = new Random();
    private ArrayList<Vehicle> vehicles = new ArrayList<Vehicle>();

    private JLabel messageJLabel; // displays vehicle that was added
    private JButton addBicycleJButton;
    private JButton addCarJButton;
    private JButton doneJButton;
    private Color background; // background color of application

public Street() {

    super("Street Simulation");

    background = Color.LIGHT_GRAY;

    messageJLabel = new JLabel("No vehicles added.");

    addBicycleJButton = new JButton("Add Bicycle");
    addBicycleJButton.addActionListener(

    new ActionListener() // anonymous inner class
            {
                public void actionPerformed(ActionEvent e) {
                    background = Color.LIGHT_GRAY;
                    Bicycle b = new Bicycle(2, 0);
                    vehicles.add(b);
                    messageJLabel.setText(b.toString()
                            + " added to vehicles");
                    repaint();

                } // end method actionPerformed
            } // end anonymous inner class
            ); // end call to addActionListener
    addCarJButton = new JButton("Add Car");
    addCarJButton.addActionListener(

    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            background = Color.LIGHT_GRAY;
            Car c = new Car(4, 0);
            vehicles.add(c);
            messageJLabel.setText(c.toString() + " added to vehicles");
            repaint();

        } // end method actionPerformed
    } // end anonymous inner class
            );// end call to addActionListener

    doneJButton = new JButton("Done");
    doneJButton.addActionListener(

    new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // code to exit goes here
            background = Color.LIGHT_GRAY;

            //I would like to have the jframe running in the background after this button is pushed.

            // System.exit(0);
            repaint();

        } // end method actionPerformed
    } // end anonymous inner class
            );// end call to addActionListener

    setLayout(new FlowLayout());
    add(addBicycleJButton);
    add(addCarJButton);
    add(doneJButton);

    add(messageJLabel);

} // end street constructor

JFrame类具有setVisible(boolean)方法,该方法可用于更改JFrame的可见性。 例如, this.setVisible(false); 隐藏它。

请参阅使用多个JFrame,良好/不良做法? 由于某些原因,您不应该避免当前的设计/想法。

更好的设计是使用CardLayout ,有关更多详细信息,请参见如何使用CardLayout

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM