Question

I have a Solitaire program that contains two different games. To access the games I have a menu bar with a Game Menu containing Carpet Solitaire and Clock Solitaire.

By default the program starts up in Carpet solitaire and I would like to choose Game -> Clock Solitaire then have a new window pop up with clock solitaire and the old Carpet solitaire window to close.

Currently my program will open the clock window but will not close the old Carpet window.

public void clockGame() {
    JButton[] buttons = {
            new JButton("Close"), new JButton("New Game")
    };

    final JDialog     dialog     = new JDialog(GUI, "Click a button");
    final JOptionPane optionPane = new JOptionPane("Would you like to start a new game of Clock Solitaire?", JOptionPane.INFORMATION_MESSAGE, JOptionPane.INFORMATION_MESSAGE, null, buttons, buttons[1]);

    buttons[0].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            dialog.setVisible(false);
        }
    });

    buttons[1].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // What can I put here to close the Carpet Window
            new ClockSolitaire(); 
            dialog.setVisible(false);
        }
    });

    dialog.setContentPane(optionPane);
    dialog.pack();
    dialog.setLocationRelativeTo(GUI);
    dialog.setVisible(true);
}

What can I add to the second actionPerformed so the old window closes?

Was it helpful?

Solution 2

If you want to use one JFrame then you could create a private JPanel where you would repaint it depending on what game he choose...

else if you want only 2 JFrames then you would need to create a reference variable to each JFrame. Meaning that you need to remove the 'new JFrame' for each click so that you gain control over it

in my case i would do;

private JFrame clockSolitaireFrame;

the ClockSolitaire class would use clockSolitaire variable to display the UI and use that variable to be able to close the frame in future. the code would look similar to this;

    buttons[1].addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        clockSolitaireFrame.dispose();
        new ClockSolitaire(); 
        dialog.setVisible(false);
    }
});

OTHER TIPS

You are painting yourself in a corner by having your class extend JFrame, forcing you to create and display JFrames, when often more flexibility is called for. A better solution: don't swap JFrames. Rather create JPanels and show them and swap them in one JFrame using a CardLayout.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top