![](/img/trans.png)
[英]How can I read a String array index from a JComboBox into a JLabel?
[英]Event for JComboBox array and show information at the JLabel Array
我有這樣的JComboBox數組和JLabel數據當我在comboBox [0] .setSelectItem(4);中選擇每個JComboBo示例中的值時,我將在這里做什么來使JLabel返回相應的。 當comboBox [4] .setSelectedItem(2);標簽[0]將獲得文本為4; 標簽[4]將獲得文本為2
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
public class Example extends javax.swing.JFrame implements ItemListener {
JComboBox[] comboBox = new JComboBox[5];
JLabel[] label = new JLabel[5];
public void test() {
for (int i = 0; i < label.length; i++) {
comboBox[i] = new JComboBox();
label[i] = new JLabel();
add(comboBox[i]);
add(label[i]);
for (int j = 0; j <= 10; j++) {
comboBox[i].addItem(j);
}
comboBox[i].addItemListener(this);
}
}
@Override
public void itemStateChanged(ItemEvent e) {
// What i will do here to make the JLabel return corresponding when I
// select the values in each JComboBox
/*
* Example when comboBox[0].setSelectItem(4); the label[0] will get the
* text is 4 when the comboBox[4].setSelectedItem(2); the lable[4] will
* get the text is 2
*/
}
}
請任何人幫助我:(
JComboBox
有方法
public int getSelectedIndex()
使用它來獲取索引,將索引轉換為字符串並設置為JLabel
。
1)您可以借助於將組件直接添加到JFrame
add(comboBox[i]); add(label[i]);
,但在這種情況下,您的JFrame
使用BorderLayout
作為默認值,並且您始終將組件添加到Center位置,在這種情況下,您將只看到一個組件。 LayoutManager教程 。
我建議您將標簽和組合框添加到單獨的面板,然后將它們添加到JFrame
。
2)你的Example
類實現了ItemListener
並將它添加到你的JComboBox
,它是正確的但在這種情況下你必須在itemStateChanged(ItemEvent e)
循環相關JLabel
。 嘗試使用JLabel
作為參數為每個comboBox添加單獨的偵聽器。
3)不是將每個值添加到comboBox,而是可以使用JComboBox
構造函數和數組參數。
我改變了你的代碼檢查它:
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends javax.swing.JFrame {
JComboBox[] comboBox = new JComboBox[5];
JLabel[] label = new JLabel[5];
public void test() {
JPanel labels = new JPanel();
JPanel boxes = new JPanel();
Object[] values = new Object[]{1,2,3,4,5,6,7,8,9,0};
for (int i = 0; i < label.length; i++) {
comboBox[i] = new JComboBox(values);
label[i] = new JLabel(" ");
boxes.add(comboBox[i]);
labels. add(label[i]);
comboBox[i].addItemListener(getListener(label[i]));
}
getContentPane().add(boxes,BorderLayout.SOUTH);
getContentPane().add(labels,BorderLayout.NORTH);
pack();
}
private ItemListener getListener(final JLabel jLabel) {
return new ItemListener() {
@Override
public void itemStateChanged(ItemEvent arg0) {
if(arg0.getStateChange() == ItemEvent.SELECTED){
jLabel.setText(((JComboBox)arg0.getSource()).getSelectedItem().toString());
}
}
};
}
public static void main(String...strings ){
Test test = new Test();
test.test();
test.setVisible(true);
}
}
並輸出:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.