基本上,我有一个 JComboBox
,当前,选定的值将显示在文本框中的组合框旁边。
但是,我想做的是从组合框中选择一个值 - 文本框中显示不同的值(此显示的值特定于从组合框中选择的值。
因此,在本例中,我在组合框中显示了尺寸,并且希望在文本字段中显示成本。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}
public ComboBox(){
String course[] = {"18x18cm (7x7inches)","18x20cm (7x8inches)",};
JFrame frame = new JFrame("Cost Calculator");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.white);
combo.setForeground(Color.black);
txt = new JTextField(25);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,200);
frame.setVisible(true);
}
}
所以我的问题是我该如何解决这个问题?
最佳答案
您应该做的是创建一个新类,以便可以将 JComboBox 和 JTextField 的数据相互关联。
class MyClass{
private String comboStr;
private String textStr;
public MyClass{
comboStr = "this goes in my combobox";
textStr = "this goes in my textfield";
}
public String toString(){
return comboStr;
}
public String getText(){
return textStr;
}
}
(您需要 toString() 以便组合框中的每个元素显示正确的文本。)
然后在监听器中,您可以使用以下命令设置 JTextField 的文本。
MyClass myObj = (MyClass)combo.getSelectedItem();
txt.setText(myObj.getText());
关于java - Jcombobox,当选择某个项目时,显示一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9247973/