If we want the radio buttons to remain in an "XOR" state, we have to add them to a group of buttons, which is almost the same as the old AWT approach but more flexible. An example of the program to be shown below is that some abstruactbutton can be added to a buttongroup.
to avoid repeating some code, this program uses maps to make different types of button groups in the afterlife. This is seen in Makebpanel, Makebpanel creates a button group and a JPanel, and each string in the array is the Makebpanel second argument that adds a class object that is declared by its first argument:
: Buttongroups.java//Uses reflection to create groups of different//types of AbstractButton.
Package c13.swing;
Import java.awt.*;
Import java.awt.event.*;
Import javax.swing.*;
Import javax.swing.border.*;
Import java.lang.reflect.*; public class Buttongroups extends JPanel {static string[] ids = {"June", "Ward", "Beaver", "Wally", "Eddie",
"Lumpy",};
Static JPanel Makebpanel (Class bclass, string[] IDs) {Buttongroup bg = new Buttongroup ();
JPanel JP = new JPanel ();
String title = Bclass.getname ();
title = Title.substring (Title.lastindexof ('. ') + 1);
Jp.setborder (new Titledborder (title));
for (int i = 0; i < ids.length i++) {AbstractButton ab = new JButton ("failed"); try {//Get the Dynamic constructor method//That takes a String argument:constructor ctor = BC
Lass.getconstructor (new class[] {string.class}); Create a new Object:ab = (AbstractButton) cTor.newinstance (new Object[]{ids[i]});
catch (Exception ex) {System.out.println ("can ' t create" + bclass);
Bg.add (AB);
Jp.add (AB);
return JP;
Public buttongroups () {Add (Makebpanel (Jbutton.class, IDS));
Add (Makebpanel (Jtogglebutton.class, IDS));
Add (Makebpanel (Jcheckbox.class, IDS));
Add (Makebpanel (Jradiobutton.class, IDS));
public static void Main (String args[]) {show.inframe (New buttongroups (), 500, 300); }
} ///:~
The border title is removed by the class name from all the path information. AbstractButton initialized to a JBUTTON,JBUTTONR label occurs "Invalid", so if we ignore this exception message, we will see the problem on the screen all the time. The GetConstructor () method produces a builder object with the GetConstructor () method to place the variable array type into the class array, and then all we have to do is call newinstance (), through which an array object contains our current argument- -In this case, the string in the IDs array.
This adds some more complex content to this simple program. In order for the "XOR" behavior to have a button, we create a group of buttons and add each button to the group we need. When we run this program, we notice that all the buttons except JButton will show us the "XOR" behavior.