我的程序以JFrame中带有文本字段的图片开始。当用户输入"start"时,我希望它关闭图片JFrame并打开另一个包含主程序的JFrame。我尝试在图片窗口中使用
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
但它会关闭所有窗口。
我的程序以JFrame中带有文本字段的图片开始。当用户输入"start"时,我希望它关闭图片JFrame并打开另一个包含主程序的JFrame。我尝试在图片窗口中使用
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
但它会关闭所有窗口。
JFrame.setVisible
可以根据参数隐藏或显示JFrame,而JFrame.dispose
实际上会“销毁”框架,关闭它并释放它所使用的资源。如果您打算重新打开该窗口,则应在图片帧上调用setVisible(false)
,或者在不再打开它时在图片帧上调用dispose()
,这样您的程序就可以释放一些内存。然后,在主框架上调用setVisible(true)
使其可见。 JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.dispose();
JFrame firstForm = new JFrame();
firstForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
firstForm.setSize(800, 600);
firstForm.setLocationRelativeTo(null);
firstForm.setVisible(true);
例如,通过按钮创建或打开另一个表单:
JFrame secondForm = new JFrame();
secondForm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
secondForm.setSize(800, 600);
secondForm.setLocationRelativeTo(null);
secondForm.setVisible(true);
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE)
。WindowClosing
事件进行了测试)。这是我解决该问题的方案:
public void actionPerformed(ActionEvent e) {
String userName = textField.getText();
String password = textField_1.getText();
if(userName.equals("mgm") && password.equals("12345")) {
secondFrame nF = new secondFrame();
nF.setVisible(false);
dispose();
}
else
{
JOptionPane.showMessageDialog(null, " Wrong password ");
}
}
对于NetBeans,使用当前对象的引用和 setVisible(false);
例如
private void submitActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
this.setVisible(false);//Closing the Current frame
new login().setVisible(true);// Opening a new frame
}
首先调用它
new Window().nextjframe.setVisible(true);
thisjframe.setVisible(false);
你也可以使用这个:
opens_frame frameOld= new opens_frame();
frameOld.setVisible(true);
Closing_Frame.setVisible(false);
Closing_Frame.dispose();
private void closeTheCurrentFrameAndOpenNew(java.awt.event.ActionEvent evt){
dispose();//To close the current window
YourClassName closeCurrentWindow = new YourClassName();
closeCurrentWindow.setVisible(true);//Open the new window
}