In the single-choice button operation, you can use the ItemListener interface to listen to events.
Package com. beyole. util; import java. awt. container; import java. awt. gridLayout; import java. awt. event. itemEvent; import java. awt. event. itemListener; import java. awt. event. windowAdapter; import java. awt. event. using wevent; import java. io. file; import javax. swing. borderFactory; import javax. swing. buttonGroup; import javax. swing. imageIcon; import javax. swing. JFrame; import javax. swing. JPanel; import javax. swing. JRadioButton; class MyRadio1 implements ItemListener {private String right = "f:" + File. separator + "2.png"; // define the image path private String wrong =" f: "+ File. separator + "3.png"; // defines the image path private JFrame frame = new JFrame (" Beyole "); // defines the form private Container container = frame. getContentPane (); // get the form container private JRadioButton jb1 = new JRadioButton ("male", new ImageIcon (right), true); private JRadioButton jb2 = new JRadioButton ("female ", new ImageIcon (wrong), false); private JPanel = new JPanel (); // define a panel public MyRadio1 () {panel. setBorder (BorderFactory. createTitledBorder ("select gender"); // defines a panel's border display panel. setLayout (new GridLayout (1, 3); // defines the layout. a row of three columns, ButtonGroup group = new ButtonGroup (); // defines a button group. add (this. jb1); // Add a single-choice button group to a group. add (this. jb2); // Add a single-choice button group to a group panel. add (this. jb1); // Add the single-choice button to the panel. add (this. jb2); // Add the single-choice button to the Panel jb1.addItemListener (this); // Add the listening event jb2.addItemListener (this); // Add the listening event container. add (panel); // add the panel to the container. this. frame. setSize (200,100); this. frame. setVisible (true); this. frame. addWindowListener (new WindowAdapter () {public void windowClosing (invalid wevent arg0) {System. exit (1) ;}}) ;}public void itemStateChanged (ItemEvent e) {if (e. getSource () = jb1) {jb1.setIcon (new ImageIcon (right); jb2.setIcon (new ImageIcon (wrong);} else {jb2.setIcon (new ImageIcon (right )); jb1.setIcon (new ImageIcon (wrong) ;}} public class JRadioButtonDemo1 {public static void main (String [] args) {new MyRadio1 ();}}
The above program uses ImageIcon to set two single-choice buttons for the image. After each option change, the itemStateChanged event is triggered, and then the display image of each option is modified.
Program: