How to open a new window by clicking a button

2020-07-06 08:52发布

问题:

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.

回答1:

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:



回答2:

new CLASS_NAME().setVisible(true);

eg. new NewJFrame().setVisible(true);