I want to intercept the click on a JRadioButton in a button group. More precise: When JRadioButton A is chosen and the user clicks on JRadioButton B, I want to show a Yes/No-option pane. Only when the user clicks "Yes", radio button B be will be selected. If the user clicks on "No" nothing is supposed to change. Is this or rather how is this possible?
Swing: Intercept click on a JRadiobutton
105 Views Asked by felix_w At
2
There are 2 best solutions below
0
On
Add an ItemListener to the B radio button. Refer to How to Use Radio Buttons. The listener is invoked after the selection has changed.
If the B button is selected, display a JOptionPane asking the user to confirm. Refer to How to Make Dialogs. A JOptionPane can also be closed by hitting the ESC key or pressing the X button in the top, right corner.
If the user closes the JOptionPane by clicking the YES button, we do nothing since button B is actually already selected. If the user closes the JOptionPane any other way, then we need to reset the selection to button A.
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Intercep {
private JFrame frame;
private JRadioButton aRadioButton;
private JRadioButton bRadioButton;
private void buildAndDisplayGui() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createButtons());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtons() {
JPanel panel = new JPanel();
ButtonGroup bg = new ButtonGroup();
aRadioButton = new JRadioButton("A");
bRadioButton = new JRadioButton("B");
bRadioButton.addItemListener(this::handleItem);
bg.add(aRadioButton);
bg.add(bRadioButton);
panel.add(aRadioButton);
panel.add(bRadioButton);
return panel;
}
private void handleItem(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
int result = JOptionPane.showConfirmDialog(frame,
"Are you sure?",
"Confirm",
JOptionPane.YES_NO_OPTION);
switch (result) {
case 0:
// YES
break;
case -1:
// <ESC> or 'X'
case 1:
// NO
default:
aRadioButton.setSelected(true);
}
}
}
public static void main(String args[]) {
EventQueue.invokeLater(() -> new Intercep().buildAndDisplayGui());
}
}
Note this line in the above code:
bRadioButton.addItemListener(this::handleItem);
This is referred to as a method reference.
You want to listen for
ItemEvents to know when the first button is selected (see this). You can useAbstractButton#isSelectedto check that the other button is selected. Finally, you can useJOptionPane#showConfirmDialog(Component, Object, String, int)to prompt the user for "Yes" or "No," and use something likeAbstractButton#setSelected(boolean)orButtonGroup#clearSelectionto control which buttons are selected.This should get you started down the right track.