1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
public class TestColor extends JFrame {
private JComboBox myBox;
public TestColor(){
myBox = new JComboBox(new Object[]{Color.BLACK,Color.BLUE, Color.RED});
myBox.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
getContentPane().setBackground((Color)myBox.getSelectedItem());
}
});
myBox.setRenderer(new DefaultListCellRenderer(){
@Override
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected,
boolean cellHasFocus) {
setMinimumSize(new Dimension(30,10));
setPreferredSize(new Dimension(50,20));
setText("");
if (value!=null)
setBackground((Color)value);
return this;
}});
setSize(400,150);
getContentPane().setLayout(new FlowLayout());
getContentPane().add(myBox);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new TestColor().setVisible(true);
}
} |