How to open a new window by clicking a button

Alex Jj picture Alex Jj · Mar 20, 2013 · Viewed 92.3k times · Source

As a part of my program, I need to have a button that when the user click on it, it opens a new window.

Well I guess I should have a class that make the frame and call it by the button. but I don't have any idea to start. I just got my button in the program, but it does not work. So can some tell me how to do it? or code it.

Answer

syb0rg picture syb0rg · Mar 20, 2013

Here is a simplified version of what you want to do:

JButton button = new JButton("New Frame");
button.addActionListener( new ActionActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        // Create a method named "createFrame()", and set up an new frame there
        // Call createFrame()
    }
});

You would probably want to call some method in the ActionListener rather than make the frame on actionPerformed. Maybe something like this:

public static void createFrame()
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                try 
                {
                   UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {
                   e.printStackTrace();
                }
                JPanel panel = new JPanel();
                panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
                panel.setOpaque(true);
                JTextArea textArea = new JTextArea(15, 50);
                textArea.setWrapStyleWord(true);
                textArea.setEditable(false);
                textArea.setFont(Font.getFont(Font.SANS_SERIF));
                JScrollPane scroller = new JScrollPane(textArea);
                scroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                scroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
                JPanel inputpanel = new JPanel();
                inputpanel.setLayout(new FlowLayout());
                JTextField input = new JTextField(20);
                JButton button = new JButton("Enter");
                DefaultCaret caret = (DefaultCaret) textArea.getCaret();
                caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
                panel.add(scroller);
                inputpanel.add(input);
                inputpanel.add(button);
                panel.add(inputpanel);
                frame.getContentPane().add(BorderLayout.CENTER, panel);
                frame.pack();
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
                frame.setResizable(false);
                input.requestFocus();
            }
        });
    }

What that frame should look like:

enter image description here