Java swing application, close one window and open another when button is clicked

前端 未结 7 1918
离开以前
离开以前 2020-12-03 07:56

I have a netbeans Java application that should display a JFrame (class StartUpWindow extends JFrame) with some options when the application is launched, then the user clicks

7条回答
  •  离开以前
    2020-12-03 08:45

    Here is an example:

    enter image description here

    enter image description here

    StartupWindow.java

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.SwingUtilities;
    
    
    public class StartupWindow extends JFrame implements ActionListener
    {
        private JButton btn;
    
        public StartupWindow()
        {
            super("Simple GUI");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            btn = new JButton("Open the other JFrame!");
            btn.addActionListener(this);
            btn.setActionCommand("Open");
            add(btn);
            pack();
    
        }
    
        @Override
        public void actionPerformed(ActionEvent e)
        {
            String cmd = e.getActionCommand();
    
            if(cmd.equals("Open"))
            {
                dispose();
                new AnotherJFrame();
            }
        }
    
        public static void main(String[] args)
        {
            SwingUtilities.invokeLater(new Runnable(){
    
                @Override
                public void run()
                {
                    new StartupWindow().setVisible(true);
                }
    
            });
        }
    }
    

    AnotherJFrame.java

    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class AnotherJFrame extends JFrame
    {
        public AnotherJFrame()
        {
            super("Another GUI");
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            add(new JLabel("Empty JFrame"));
            pack();
            setVisible(true);
        }
    }
    

提交回复
热议问题