Skip to content
Advertisement

How do I close a JOptionPane once a button is clicked?

I’ve seen other solutions using yes-no-cancel options but I am using an array of three options for the user to choose from as a sort of pre-launch menu for my app.
I’m sorry if my code is awful to look at, I’m still new to this.

I want to close the JOptionPane.showOptionDialog() once any of these three buttons are clicked. Not sure if Java has a method for this but if there is, I haven’t been able to find it. Thanks in advance!

static void startMenu() {
  JButton btnThreeByThree = new JButton("Easy 3x3");
  JButton btnFiveByFive = new JButton("Meduim 5x5");
  JButton btnTenByTen = new JButton("Hard 10x10");

  btnThreeByThree.addMouseListener(new MouseAdapter(){
     @Override
     public void mouseClicked(MouseEvent e) {
        GameFrame myFrame = new View.GameFrame(3, 3);
        myFrame.setVisible(true);
     }
  }); 

  btnFiveByFive.addMouseListener(new MouseAdapter(){
     @Override
     public void mouseClicked(MouseEvent e) {
        GameFrame myFrame = new View.GameFrame(5, 5);
        myFrame.setVisible(true);
     }
  }); 

  btnTenByTen.addMouseListener(new MouseAdapter(){
     @Override
     public void mouseClicked(MouseEvent e) {
        GameFrame myFrame = new View.GameFrame(10, 10);
        myFrame.setVisible(true);
     }
  }); 
  

  Object[] options = {btnThreeByThree, btnFiveByFive, btnTenByTen};

  JOptionPane.showOptionDialog(null, "Select a size to play", "Starting game...",
        JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE,
        null, options, options[0]);
  
}

Advertisement

Answer

Object[] options = {btnThreeByThree, btnFiveByFive, btnTenByTen}; 

You don’t create buttons as the options.

Instead you just pass the text and the option pane will create the buttons.

Object[] options = {"Easy 3x3", "Medium 5x5", "Hard 10x10"};

Then you need to test the int value returned from the ShopwOptionDialog() method to invoke your processing:

int result = JOptionPane.showOptionDialog(null, "Select a size to play", "Starting game...", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]);

switch (result)
{
    case 0: 
        GameFrame myFrame = new View.GameFrame(3, 3);
        myFrame.setVisible(true);
        return;
    case 1: 
        ...
}

Read the section from the Swing tutorial on Customize Button Text for an example.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement