《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: clientpropertiestest.java
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.beans.*;
public class ClientPropertiesTest extends JApplet {
JButton button = new JButton("toggle target color");
JComboBox targetCombo = new JComboBox();
JPanel[] targets = { new JPanel(),
new JPanel(),
new JPanel() };
public void init() {
Container contentPane = getContentPane();
Dimension targetPreferredSize = new Dimension(100,100);
JPanel targetPanel = new JPanel();
for(int i=0; i < targets.length; ++i) {
targets[i].setBackground(Color.blue);
targets[i].setPreferredSize(targetPreferredSize);
targetPanel.add(targets[i]);
}
targetCombo.addItem("left");
targetCombo.addItem("center");
targetCombo.addItem("right");
contentPane.setLayout(new FlowLayout());
contentPane.add(button);
contentPane.add(targetCombo);
contentPane.add(targetPanel);
button.putClientProperty("target", targets[0]);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Component c =
(Component)button.getClientProperty("target");
if(c != null) {
Color bg = c.getBackground();
c.setBackground(bg == Color.blue ?
Color.red : Color.blue);
c.repaint();
}
}
});
targetCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
button.putClientProperty(
"target",
targets[targetCombo.getSelectedIndex()]);
}
});
button.addPropertyChangeListener(
new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
if(e.getPropertyName().equals("target")) {
showStatus(
(String)targetCombo.getSelectedItem() +
" panel set as target");
}
}
});
}
public static void main(String args[]) {
final JFrame f = new JFrame();
JApplet applet = new ClientPropertiesTest();
applet.init();
f.setContentPane(applet.getContentPane());
f.setBounds(100,100,300,250);
f.setTitle("ClientPropertiesTest");
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
f.dispose();
System.exit(0);
}
});
}
}