Disposing JFrame by clicking from an inner JPanel

天大地大妈咪最大 提交于 2019-12-18 09:33:48

问题


I'm trying to dispose my JFrame by clicking a button, located on a JPanel that is placed on the JFrame that I want to close.

I tried to make a static method on the JFrame class, but ofcourse my IDE told me that wasn't going to happen.

Anyone thinking of a solution?

Thanks!


回答1:


Try this:

public class DisposeJFrame extends JFrame{
    JPanel panel = new JPanel();
    JButton button = new JButton("Dispose JFrame");

    public DisposeJFrame(){
        super();
        setTitle("Hi");
        panel.add(button);
        add(panel);
        pack();

        button.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent arg0) {
                dispose();
            }
        });
    }

    public static void main(String args[]){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                DisposeJFrame jf = new DisposeJFrame();
                    jf.setVisible(true);
            }
        });
    }
}



回答2:


Do something like this:

JButton closeFrameButton = new JButton("Close");
closeFrameButton.addActionListener(new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        ((Window) getRootPane().getParent()).dispose();
    }
});


来源:https://stackoverflow.com/questions/2358296/disposing-jframe-by-clicking-from-an-inner-jpanel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!