所以,我有一个带有按钮的框架(awt),如果你点击“同步”,它会弹出一个窗口。现在,我只是想要它,以便您可以单击该弹出窗口上的 X,然后弹出窗口将消失。我有一条评论显示我希望它消失的地方。
import java.awt.*;
import java.awt.event.*;
public class Main
{
public static void main(String[] args)
{
ActionListener listen=new MyActionListener();
Frame frame= new Frame("frame");//make the frame
Button exit=new Button("Exit");
exit.setActionCommand("Exit");
exit.addActionListener(listen);
Button Sync=new Button("Sync");
Sync.setActionCommand("Sync");
Sync.addActionListener(listen);//create Exit and Sync buttons.
frame.add(exit);
frame.add(Sync);
frame.setLayout(new GridLayout(2, 1));
frame.setSize(100,80);
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void MyActionListener(ActionEvent e)
{
System.exit(0);
}
}
class MyActionListener implements ActionListener{
public void actionPerformed(ActionEvent ae) {
String s = ae.getActionCommand();
if (s.equals("Exit")) {
System.exit(0);
}//note that the exit button DOES work, so this system is working.
if (s.equals("Sync")) {
Frame frame2= new Frame("Popup!");
frame2.setVisible(true);
frame2.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
//Remove frame2 here.
}
});
}
}
}
我之前看到过一个非常相似(如果不相同)的问题,“答案”是使用 dispose。("frame2.dispose();") 我试过了,我得到了以下错误报告:
Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - local variable frame2 is accessed from within inner class; needs to be declared final
at vexscouting.MyActionListener$1.windowClosing(Main.java:76)
at java.awt.Window.processWindowEvent(Window.java:1865)
at java.awt.Window.processEvent(Window.java:1823)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Window.dispatchEventImpl(Window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
注意:我使用的是 NetBeans