Implementing JOptionPane in Java

907 views Asked by At

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

2

There are 2 answers

4
Pshemo On BEST ANSWER
  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.
0
markspace On

I think what you're trying to do is referred to as Direct Use of the JOptionPane. Refer to the documentation for more details.

 JOptionPane pane = new JOptionPane(arguments);
 pane.set.Xxxx(...); // Configure
 JDialog dialog = pane.createDialog(parentComponent, title);
 dialog.show();