【发布时间】:2012-10-08 05:48:24
【问题描述】:
我有JComboBox 2 列,我有JButton。当我单击JButton 时,我需要分别从第一列和第二列中获取JComboBox 选定值的结果...
我该怎么做?
另外:如何设置 JComboBox 的标题?
代码:
public class Combo extends JFrame implements ActionListener{
private JComboBox combo = new JComboBox();
private JButton button = new JButton();
public Combo() {
setLayout(new FlowLayout());
combo.setRenderer(new render());
add(combo);
combo.addItem(new String[] {"1","bbb"});
combo.addItem(new String[] {"2","ff"});
combo.addItem(new String[] {"3","gg"});
combo.addItem(new String[] {"4","ee"});
add(button);
button.addActionListener(this);
pack();
}
public static void main(String[]args){
new Combo().setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==button){
System.out.println(combo.getSelectedItem());
}
}
}
class render extends JPanel implements ListCellRenderer{
private JLabel label1 = new JLabel();
private JLabel label2 = new JLabel();
private JLabel label3 = new JLabel();
private JLabel label4 = new JLabel();
private JLabel label5 = new JLabel();
public render() {
setLayout(new GridLayout(2,5));
add(label1);
add(label2);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String[] values = (String[]) value;
label1.setText(values[0]);
label2.setText(values[1]);
if(index ==0){
label1.setForeground(Color.red);
label2.setForeground(Color.red);
}else{
label1.setForeground(Color.white);
label2.setForeground(Color.white);
}
return this;
}
}
谢谢。
【问题讨论】:
-
问题是两个问题,header不是适用于JComboBox的术语。您必须给出该术语有意义的示例或上下文(但不作为其他问题的一部分)。可以理解的是,答案并没有表现出理解问题第二部分的能力。您应该编辑问题以删除第二个问题,并从 cmets 中删除该附加问题的重复。尝试单独查找第二个问题,如果该问题不存在,请将其作为单独的原始帖子而不是作为评论提出。
标签: java swing jbutton jcombobox listcellrenderer