OnJava8-Examples/gui/ButtonGroups.java

54 lines
1.7 KiB
Java
Raw Normal View History

2015-04-20 15:36:01 -07:00
//: gui/ButtonGroups.java
// Uses reflection to create groups
// of different types of AbstractButton.
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.lang.reflect.*;
import static net.mindview.util.SwingConsole.*;
public class ButtonGroups extends JFrame {
private static String[] ids = {
"June", "Ward", "Beaver", "Wally", "Eddie", "Lumpy"
};
static JPanel makeBPanel(
Class<? extends AbstractButton> kind, String[] ids) {
ButtonGroup bg = new ButtonGroup();
JPanel jp = new JPanel();
String title = kind.getName();
title = title.substring(title.lastIndexOf('.') + 1);
jp.setBorder(new TitledBorder(title));
for(String id : ids) {
AbstractButton ab = new JButton("failed");
try {
// Get the dynamic constructor method
// that takes a String argument:
Constructor ctor =
kind.getConstructor(String.class);
// Create a new object:
ab = (AbstractButton)ctor.newInstance(id);
2015-05-06 12:09:38 -07:00
} catch(NoSuchMethodException |
SecurityException |
InstantiationException |
IllegalAccessException |
IllegalArgumentException |
InvocationTargetException ex) {
2015-04-20 15:36:01 -07:00
System.err.println("can't create " + kind);
}
bg.add(ab);
jp.add(ab);
}
return jp;
}
public ButtonGroups() {
setLayout(new FlowLayout());
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) {
run(new ButtonGroups(), 500, 350);
}
} ///:~