ItemListener iListener = new ItemListener() {
public void itemStateChanged(ItemEvent event) {
Icon girlIcon = new ImageIcon("girl-r.jpg");
Icon boyIcon = new ImageIcon("boy-r.jpg");
AbstractButton aButton = (AbstractButton)event.getSource();
int state = event.getStateChange();
String newLabel;
Icon newIcon;
if (state == ItemEvent.SELECTED) {
newLabel = "Girl";
newIcon = girlIcon;
} else {
newLabel = "Boy";
newIcon = boyIcon;
}
aButton.setText(newLabel);
aButton.setIcon(newIcon);
}
};
自定义JCheckBoxMenuItem观感
图6-3显示了预安装的观感类型集合下JCheckBoxMenuItem的外观。
表6-12列出了JCheckBoxMenuItem的UIResource相关的属性。JCheckBoxMenuItem组件具有19个不同的属性。
JCheckBoxMenuItem UIResource元素
属性字符串
对象类型
CheckBoxMenuItem.acceleratorFont
Font
CheckBoxMenuItem.acceleratorForeground
Color
CheckBoxMenuItem.acceleratorSelectionForeground
Color
CheckBoxMenuItem.actionMap
ActionMap
CheckBoxMenuItem.arrowIcon
Icon
CheckBoxMenuItem.background
Color
CheckBoxMenuItem.border
Border
CheckBoxMenuItem.borderPainted
Boolean
CheckBoxMenuItem.checkIcon
Icon
CheckBoxMenuItem.commandSound
String
CheckBoxMenuItem.disabledForeground
Color
CheckBoxMenuItem.font
Font
CheckBoxMenuItem.foreground
Color
CheckBoxMenuItem.gradient
List
CheckBoxMenuItem.margin
Insets
CheckBoxMenuItem.opaue
Boolean
CheckBoxMenuItem.selectionBackground
Color
CheckBoxMenuItem.selectionForeground
Color
CheckBoxMenuItemUI
String
与CheckboxMenuItem.checkIcon属性键值相关联的Icon是显示在JCheckBoxMenuItem上的图标。如果我们不喜欢默认图标,我们可以使用下面的代码行进行修改,在这里假定已经定义并创建了新图标:
UIManager.put("CheckBoxMenuItem.checkIcon", someIcon);为了使得新图标可以显示合适的选中图像,Icon实现必须其paintIcon()方法内检测关联的菜单组件状态。第4章所创建的DiamondIcon对于这个图标并不起作用,因为他并不检测其状态组件。相反,状态是在构造是确定的。列表6-4列出了一个可以使用的图标类。
package net.ariel.ch06; import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Polygon; import javax.swing.AbstractButton;
import javax.swing.Icon; public class DiamondAbstractButtonStateIcon implements Icon { private final int width = 10;
private final int height = 10;
private Color color;