62,621
社区成员
发帖
与我相关
我的任务
分享public class Test2 extends JFrame {
static Object[][] item = {{"A", Color.BLUE, Color.WHITE},{"B", Color.BLUE, Color.WHITE},
{"C", Color.BLUE, Color.WHITE}};
static JComboBox comboBox = null;
public Test2(){
comboBox = new JComboBox(item);
comboBox.setRenderer(new ComboBoxListCellRenderer());
comboBox.setBackground(Color.white);
this.add(comboBox, BorderLayout.NORTH);
comboBox.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
//方法1: int s = ((JComboBox)e.getSource()).getSelectedIndex();
//方法2: String s = (String)((JComboBox)e.getSource()).getSelectedItem();
// System.out.println(s);
}
});
}
public static void main(String[] args){
Test2 test2 = new Test2();
test2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
test2.setSize(200, 100);
test2.setVisible(true);
}
}public class ComboBoxListCellRenderer implements ListCellRenderer{
DefaultListCellRenderer defaultRanderer = new DefaultListCellRenderer();
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus){
String theText = null;
Color backGround = null;
Color foreGround = null;
JLabel renderer = (JLabel)defaultRanderer.getListCellRendererComponent(list,
value, index, isSelected, cellHasFocus);
if(value instanceof Object[]){
Object[] values = (Object[])value;
theText = (String)values[0];
backGround = (Color)values[1];
foreGround = (Color)values[2];
}
if(isSelected){
renderer.setBackground(backGround);
renderer.setForeground(foreGround);
}
renderer.setText(theText);
list.setSelectionBackground(Color.WHITE);
return renderer;
}
}
//方法2:
String s = ((JComboBox)e.getSource()).getSelectedItem().toString();