基本上,我有一个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());

07-24 09:45
查看更多