我的 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;
}
}
谢谢。
您的项目是字符串数组,因此您可以按以下方式打印所选项目:
System.out.println(Arrays.toString((String[])combo.getSelectedItem()));
编辑:
String[] selectedItem = (String[])combo.getSelectedItem();
for (int i = 0; i < selectedItem.length; i++){
System.out.println(String.format("item %s = %s", i, selectedItem[i]));
}
或不久,如果您需要的是第一项-(String[])combo.getSelectedItem())[0]
。
要显示所选元素的第一个值,您可以使用:
System.out.println(((String[])combo.getSelectedItem())[0]);
我认为这可能比以前的答案容易:
(String) comboBox.getSelectedItem();