在 actionPerformed 方法中关闭 JFrame(JFrame 是 private static void createGUI())
Close JFrame in actionPerformed-method (JFrame is private static void createGUI())
我的大部分代码都是从 oracle 示例中复制的,所以我认为至少我没有添加的代码应该是正确的,我不想更改它。但是在 oracle 代码中我无法执行此行以正确关闭我的 JFrame:frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
private static void createGUI() {
JFrame frame = new JFrame("NameChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==skipButton){
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); WindowEvent.WINDOW_CLOSING)); // does not work ofc
}
}
如何在 actionPerformed 方法中关闭我的 JFrame 而不会破坏打开 JFrame 的正确方式?
或者此 oracle 代码是否仅适用于示例而不适用于实际应用程序?
您应该 frame
像这样创建一个实例字段:
private static JFrame frame;
private static void createGUI()
{
frame = new JFrame( "NameChooser" );
...
}
我的大部分代码都是从 oracle 示例中复制的,所以我认为至少我没有添加的代码应该是正确的,我不想更改它。但是在 oracle 代码中我无法执行此行以正确关闭我的 JFrame:frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
private static void createGUI() {
JFrame frame = new JFrame("NameChooser");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
...
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createGUI();
}
});
}
public void actionPerformed(ActionEvent e) {
if (e.getSource()==skipButton){
frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING)); WindowEvent.WINDOW_CLOSING)); // does not work ofc
}
}
如何在 actionPerformed 方法中关闭我的 JFrame 而不会破坏打开 JFrame 的正确方式?
或者此 oracle 代码是否仅适用于示例而不适用于实际应用程序?
您应该 frame
像这样创建一个实例字段:
private static JFrame frame;
private static void createGUI()
{
frame = new JFrame( "NameChooser" );
...
}