Search code examples
javaswingjframejbutton

Java - Close Window on Event


people of the internet.

I want to have a sort of start screen for a game ive been writing. Thus far it features 4 Buttons for each one of the 4 Players that change color on click from red to green and vice versa representing their individual "ready"-status if that makes sense. I used JFrame and JButtons.

Now i want that window to close if every one of those Buttons is currently set to "ready" aka button.getBackground() == Color.GREEN.

Any suggestions as to which EventListeners to use for this/implementation tips/code snippets would be greatly appreciated since my research on Windowclosing on Event didnt bring up much for me.

Thank you in advance and Greetings.


Solution

  • Since you're awaiting and acting on button presses, the most logical listener would be an ActionListener.

    Consider making the buttons JToggleButtons, and then in your listener querying each button to see if it is selected (isSelected()) and if so, launch your program. As a side bit, I'd consider making the intro window a JDialog and not a JFrame, either that or making it a JPanel and swapping it out via a CardLayout when necessary.

    For example:

    import java.awt.Color;
    import java.awt.Dialog.ModalityType;
    import java.awt.Dimension;
    import java.awt.Window;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.List;
    import javax.swing.*;
    
    public class AreWeReady extends JPanel {
        List<AbstractButton> buttons = new ArrayList<>();
        private int userCount;
    
        public AreWeReady(int userCount) {
            this.userCount = userCount;
            ButtonListener buttonListener = new ButtonListener();
            for (int i = 0; i < userCount; i++) {
                JButton btn = new JButton("User " + (i + 1));
                buttons.add(btn);
                btn.addActionListener(buttonListener);
                add(btn);
            }
        }
    
        private class ButtonListener implements ActionListener {
            @Override
            public void actionPerformed(ActionEvent e) {
                AbstractButton btn = (AbstractButton) e.getSource();
                Color c = Color.GREEN.equals(btn.getBackground()) ? null : Color.GREEN;
                btn.setBackground(c);
    
                for (AbstractButton button : buttons) {
                    if (!Color.GREEN.equals(button.getBackground())) {
                        // if any button does not have a green background
                        return;    // leave this method
                    }
                }
    
                // otherwise if all are green, we're here
                Window win = SwingUtilities.getWindowAncestor(btn);
                win.dispose();
                // else launch your gui
            }
        }
    
        private static void createAndShowGui() {
            int userCount = 4;
            AreWeReady areWeReadyPanel = new AreWeReady(userCount);
    
            JFrame frame = new JFrame("Main Application");
            frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frame.getContentPane().add(Box.createRigidArea(new Dimension(400, 300)));
            frame.pack();
            frame.setLocationByPlatform(true);
    
            JDialog dialog = new JDialog(frame, "Are We Ready?", ModalityType.APPLICATION_MODAL);
            dialog.add(areWeReadyPanel);
            dialog.pack();
            dialog.setLocationByPlatform(true);
            dialog.setVisible(true);
    
            // this is only reached when the modal dialog above is no longer visible
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGui();
                }
            });
        }
    }