Disposing JFrame by clicking from an inner JPanel

前端 未结 2 1229
無奈伤痛
無奈伤痛 2020-12-22 02:26

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

相关标签:
2条回答
  • 2020-12-22 02:52

    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);
                }
            });
        }
    }
    
    0 讨论(0)
  • 2020-12-22 03:03

    Do something like this:

    JButton closeFrameButton = new JButton("Close");
    closeFrameButton.addActionListener(new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            ((Window) getRootPane().getParent()).dispose();
        }
    });
    
    0 讨论(0)
提交回复
热议问题