Search code examples
javaswingjoptionpane

Implementing JOptionPane in Java


I created this popup window which will show up in response to a button being clicked in my gui. I have two questions regarding this.

  1. How do I get rid of the text field below the radio buttons?
  2. I need to check which radio button was selected once the ok button is clicked but I didn't create that button. So how would I implement the actionPerformed function for that?

My code:

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    if(evt.getSource() == jButton2)
         optionPopup();
} 

private void optionPopup(){
    JPanel panel = new JPanel();
    JRadioButton undergraduateButton = new JRadioButton();
    JRadioButton graduateButton = new JRadioButton();
    ButtonGroup group = new ButtonGroup();

    undergraduateButton.setText("Option A");
    graduateButton.setText("Option B");
    group.add(undergraduateButton);
    group.add(graduateButton);
    panel.add(undergraduateButton);
    panel.add(graduateButton);

    JOptionPane.showInputDialog(panel);

enter image description here


Solution

    1. Use JOptionPane.showMessageDialog instead of JOptionPane.showInputDialog

      if you still want to have ? icon instead of ! one, use

      JOptionPane.showMessageDialog(null, panel, "title", JOptionPane.QUESTION_MESSAGE);
      

      you can also remove icon by using JOptionPane.PLAIN_MESSAGE

      If you want to make sure that client pressed OK button use

      int response = JOptionPane.showConfirmDialog(null, panel, "title", JOptionPane.PLAIN_MESSAGE);  
      

      If response will be -1 it means window was closed by X button, if it was 0 user pressed OK.

      More info at: https://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html


    1. Use undergraduateButton.isSelected() and graduateButton.isSelected() to see if one of them was selected.