从JComboBox获取价值 [英] Get Value from JComboBox
本文介绍了从JComboBox获取价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有 JComboBox
有2列,我有 JButton
。当我单击 JButton
时,我需要分别从第一列和第二列中获取 JComboBox
选定值的结果...
I have JComboBox
with 2 columns and I have JButton
. When I click the JButton
, I need to get the result of the JComboBox
selected value from first column and seconds column separately...
我该怎么做?
另外:如何设置JComboBox的标题?
Also: how do I set the header of that 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;
}
}
谢谢。
推荐答案
您的商品是字符串数组,因此您可以按如下方式打印所选商品:
Your items are arrays of strings, so you can print the selected item as follows:
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]));
}
或者如果您需要的是第一项 - (字符串[])combo.getSelectedItem())[0]
。
Or shortly if all you need is the first item - (String[])combo.getSelectedItem())[0]
.
这篇关于从JComboBox获取价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文