2014-11-22 51 views
1

我有一個jframe作爲程序的一部分,用戶將通過按下添加按鈕來填充數組列表。當他們完成填充數組列表時,我希望他們在程序繼續運行時單擊完成按鈕來隱藏jframe。當單擊按鈕時隱藏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 
+1

? 'setVisible(false)'? '處置()'?你知道在一個程序中有一堆JFrames通常是新手程序的一個標誌,並且經常表明該設計可能從改變中受益。相反,爲什麼不使用CardLayout更改視圖。或者如果你需要一個模態窗口,然後使用模態JDialog。 – 2014-11-22 22:01:22

+2

請參閱[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/q/9554636/418556)。更好的設計是使用'CardLayout',請參閱[如何使用CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html)以獲得更多詳細信息 – MadProgrammer 2014-11-22 22:06:50

+0

爲了更快地獲得更好的幫助,發佈[MCVE](http://stackoverflow.com/help/mcve)(最小完整可驗證示例)或[SSCCE](http://www.sscce.org/)(簡短,獨立,正確的示例)。 – 2014-11-23 01:05:13

回答

1

JFrame類具有可用於改變一個JFrame的可視性的方法setVisible(boolean)。例如,this.setVisible(false);可以隱藏它。