-1

I have made a panel which contains two radio groups of buttons. You can find the result of JPanel in the image below. Then I used the below code to add this panel to a JOptionPane box:

OptionsForDisjunctionNodes optionsForDisjunctionNodes=new  OptionsForDisjunctionNodes();
JPanel p=optionsForDisjunctionNodes.getPanel();
int option = JOptionPane.showConfirmDialog(null, p, "Decision on Disjunctive Nodes", JOptionPane.OK_CANCEL_OPTION,JOptionPane.INFORMATION_MESSAGE);
if (JOptionPane.OK_OPTION == option) {
    // Print selected radio button in each group. How?
} else {
    // Do something else. 
}

Let's say the name of group boxes are buttonGroup1, and buttonGroup2

I need to when the user click on Ok button, I print the selected label in both groups

enter image description here

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Sal-laS
  • 11,016
  • 25
  • 99
  • 169
  • 1
    A lost of the answer depends on the design of `OptionsForDisjunctionNodes`. For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Apr 20 '17 at 08:17
  • The `OptionsForDisjunctionNodes` is a `JPanel` which contains 2 `groupBox` – Sal-laS Apr 20 '17 at 08:22
  • An MCVE / SSCCE is code, not a (poor) textual explanation. And while I remember: see also [How to create great screenshots?](http://meta.stackexchange.com/q/99734/155831) (Alt+PrintScreen on Windows is your friend.) – Andrew Thompson Apr 20 '17 at 08:24

2 Answers2

-1

Let OptionsForDisjunctionNodes add a listener to the radio buttons. And when pressed have it store whatever option was pressed last.

Then also provide getters on OptionsForDisjunctionNodes to retrieve this information.


Alternatively, you still provide getters in OptionsForDisjunctionNodes but have them loop over the button group to find which option is selected.

Check this stackoverflow question for ideas on how to do that exactly.

Community
  • 1
  • 1
Imus
  • 802
  • 6
  • 11
-1

You could work with action commands on the JRadioButtons like this:

ButtonGroup buttonGroup1=new ButtonGroup();
JRadioButton r1=new JRadioButton();
JRadioButton r2=new JRadioButton();
r1.setActionCommand("hello");

buttonGroup1.add(r1);
buttonGroup1.add(r2);

your if would then look like this:

if (JOptionPane.OK_OPTION == option) {
    System.out.println(buttonGroup1.getSelection().getActionCommand());
    System.out.println(buttonGroup2.getSelection().getActionCommand());
} else {

}

for buttonGroup1 it would print hello in this case if r1 is selected

XtremeBaumer
  • 6,275
  • 3
  • 19
  • 65