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 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class myJFrame extends JFrame {
JComboBox jcb = new JComboBox();
DefaultComboBoxModel model = new DefaultComboBoxModel();
JTextField jtf = new JTextField(10);
public myJFrame() {
super();
model.addElement(new MyItem(Color.BLUE,"toto"));
model.addElement(new MyItem(Color.RED,"titi"));
model.addElement(new MyItem(Color.GREEN,"tata"));
model.addElement(new MyItem(Color.YELLOW,"tutu"));
jcb.setModel(model);
jcb.setRenderer(new MyListCellRenderer());
jtf.addActionListener(new ActionListener(){
public void actionPerformed (ActionEvent e) {
DefaultComboBoxModel mod = (DefaultComboBoxModel)jcb.getModel();
mod.addElement(new MyItem(Color.BLACK,jtf.getText()));
jcb.updateUI();
}
});
getContentPane().setLayout(new GridLayout(2,1));
getContentPane().add(jcb);
getContentPane().add(jtf);
setSize(200,200);
setVisible(true);
}
public static void main (String arg[]) {
myJFrame frame = new myJFrame();
}
}
class MyListCellRenderer extends DefaultListCellRenderer {
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list,value,index,isSelected,cellHasFocus);
MyItem mi = (MyItem)value;
setForeground(mi.getColor());
setText(mi.getText());
return this;
}
}
class MyItem {
Color colorItem;
String textItem;
public MyItem(Color c, String s) {
colorItem = c;
textItem = s;
}
public Color getColor() {
return colorItem;
}
public String getText() {
return textItem;
}
} |
Partager