我創建一個簡單的任務管理器,我遇到的問題是當我單擊JButton時我想打開一個新的JFrame。窗口打開,但問題是多個窗口打開。我有兩個類App(Main)和NewTask。如果有人可以看看代碼,看看我做錯了,那很好,如果我發佈的代碼太多,很抱歉,謝謝。使用JButton問題打開一個新的JFrame
App Class
JButton btnNewTask = new JButton("New Task");
btnNewTask.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
JFrame frame = new JFrame ("New Task");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
//frame.getContentPane().add (new NewTask());
frame.pack();
frame.setVisible (true);
}
});
btnNewTask.setBounds(10, 216, 116, 23);
contentPane.add(btnNewTask);
NewTask Class
/**
* Launch the application.
*/
//public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
try
{
NewTask frame = new NewTask();
frame.setVisible(true);
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public NewTask()
{
setTitle("New Task");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
對不起,我剛剛注意到我把這一行註釋掉了//frame.getContentPane().add(new NewTask());有了這個評論,它只打開一個空白的JFrame一次。 – user1857403
看到這個:[使用多個JFrames,好/壞實踐?](http://stackoverflow.com/questions/9554636/the-use-of-multiple-jframes-good-bad-practice)而是使用'JDialog '或['CardLayout'](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html)。也不要使用null/absolute佈局,而應使用適當的['LayoutManger'](http://docs.oracle.com/javase/tutorial/uiswing/layout/index.html)。並請發佈[SSCCE](http://sscce.org)(具體可編譯代碼) –