//: 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 = bClass.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);
}
} ///:~
P.472
这个例程中24秆的AbstractButton ab = new JButton("failed");为什么不写在循环的外面?37、38行的bg.add(ab);jp.add(ab);原以为应该是bg.add(ab);jp.add(bg);上机后才知道只有这样写才行。
标签:ab,Java,String,--,44,jp,ids,add,new From: https://blog.51cto.com/u_16183536/8706682