Search code examples
javaswingmenujframejoptionpane

How do I open new windows from menubars?


This is my code so far:

public static void main(String[] args){
    JFrame frame = new JFrame("Breakout!");
    frame.setLocation(300, 300);
    //Making the menubar
        JMenuBar mb = new JMenuBar();
        frame.setJMenuBar(mb);
        JMenu fileMenu = new JMenu("File");
        mb.add(fileMenu);
        JMenuItem newAction =   new JMenuItem("About");
        fileMenu.add(newAction);
        newAction.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("open new window here");
            }
        });
    BreakoutCourt c = new BreakoutCourt();
    frame.add(c);
    frame.pack();
    frame.setResizable(false);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

I am making a Breakout game. I want to make an About window that displays information about the game (like, how to play it and so on). How would I go about doing that? Thank you for the help! I'm very new to Java Swing, so yeah.


Solution

  • You could do a simple one with the message type of JOptionPane:

    JOptionPane.showMessageDialog(frame, "Breakout! v1.0");
    

    (You'll need to make the frame final to do this, since it's being accessed from within the anonymous action listener).

    For more control over what is displayed, and whether it should be modal or not, you could look at JDialog. There's an overview of using dialogs in Swing here: http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html.