Java 单击按钮关闭 JFrame
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2352727/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Closing JFrame with button click
提问by Mohit BAnsal
I have the jButton1 private member of JFrame and i wanted to close the frame when the button is clicked.
我有 JFrame 的 jButton1 私有成员,我想在单击按钮时关闭框架。
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
}
});
I wanted to do super.close()
but could not find close for super. Is there some way to refer to the JFrame
我想做super.close()
但找不到超级接近。有没有办法引用JFrame
回答by Roman
You cat use setVisible ()
method of JFrame (and set visibility to false
) or dispose ()
method which is more similar to close
operation.
您可以使用setVisible ()
JFrame 的方法(并将可见性设置为false
)或dispose ()
更类似于close
操作的方法。
回答by Anton
You will need a reference to the specific frame you want to close but assuming you have the reference dispose()
should close the frame.
您将需要对要关闭的特定帧的引用,但假设您有引用dispose()
应该关闭该帧。
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
frameToClose.dispose();
}
});
回答by lins314159
It appears to me that you have two issues here. One is that JFrame does not have a close
method, which has been addressed in the other answers.
在我看来,您在这里有两个问题。一个是 JFrame 没有close
方法,这已在其他答案中解决。
The other is that you're having trouble referencing your JFrame. Within actionPerformed
, super
refers to ActionListener. To refer to the JFrame instance there, use MyExtendedJFrame.super
instead (you should also be able to use MyExtendedJFrame.this
, as I see no reason why you'd want to override the behaviour of dispose
or setVisible
).
另一个是您在引用 JFrame 时遇到问题。在 中actionPerformed
,super
指的是 ActionListener。要在那里引用 JFrame 实例,请MyExtendedJFrame.super
改用(您也应该能够使用MyExtendedJFrame.this
,因为我认为没有理由要覆盖dispose
or的行为setVisible
)。
回答by Shriji Infotech
You can use super.dispose() method which is more similar to close operation.
您可以使用更类似于关闭操作的 super.dispose() 方法。
回答by acp
JButton b3 = new JButton("CLOSE");
b3.setBounds(50, 375, 250, 50);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});