我有JComboBox
2列,我有JButton
。當我點擊JButton
時,我需要分別從第一列和第二列中得到JComboBox
選定值的結果...從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;
}
}
感謝。
真的非常感謝..它的工作..但如何,如果我只需要第一個值?我需要單獨的值 –
@JasonAmavisca請參閱上次編輯 – tenorsax
我..很多感謝^^ ..但如何設置它的標題?爲很多請求道歉.. –