如何在Java中关闭单个框架?

时间:2012-11-03 15:22:10

标签: java awt frame

所以,我有一个带有按钮的框架(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

0 个答案:

没有答案