《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.plaf.basic.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
public class Test extends JApplet {
public void init() {
Container contentPane = getContentPane();
final JSlider slider = new JSlider();
final JCheckBox checkBox = new JCheckBox("Annotate");
slider.setUI(new AnnotatedSliderUI(slider));
contentPane.setLayout(new FlowLayout());
contentPane.add(checkBox);
contentPane.add(slider);
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
boolean selected = checkBox.isSelected();
slider.putClientProperty(
AnnotatedSliderUI.ANNOTATE_PROPERTY,
selected ? Boolean.TRUE : Boolean.FALSE);
slider.repaint();
}
});
}
}
class AnnotatedSliderUI extends BasicSliderUI {
public static String ANNOTATE_PROPERTY =
"AnnotatedSliderUI.annotate";
boolean annotate = false;
public AnnotatedSliderUI(JSlider slider) {
super(slider);
}
public Dimension getPreferredSize(JComponent c) {
Dimension d = super.getPreferredSize(c);
return new Dimension(d.width,d.height+20);
}
public void paint(Graphics g, JComponent c) {
if(annotate) {
JSlider slider = (JSlider)c;
int v = slider.getValue();
g.setColor(UIManager.getColor("Label.foreground"));
g.setFont(new Font("Dialog", Font.PLAIN, 28));
g.drawString((new Integer(v)).toString(),10,33);
}
super.paint(g,c);
}
protected PropertyChangeListener
createPropertyChangeListener(JSlider slider) {
return new AnnotatePropertyListener();
}
protected class AnnotatePropertyListener
extends BasicSliderUI.PropertyChangeHandler {
public void propertyChange(PropertyChangeEvent e) {
System.out.println("property changed");
super.propertyChange(e);
String name = e.getPropertyName();
if(name.equals(ANNOTATE_PROPERTY)) {
System.out.println("property changed");
if(e.getNewValue() != null) {
annotate =
((Boolean)e.getNewValue()).booleanValue();
}
}
}
}
}