如何根据JComboBox选择更改JTextField

时间:2013-05-15 02:14:58

标签: java swing jtextfield jcombobox itemlistener

这只是我正在上学的一个愚蠢的计划,但我遇到了一些麻烦。我有一个JComboBox,根据用户选择我想要更改文本字段。然而,我遇到了一些麻烦,因为现在程序编译并运行,但文本字段不会改变。我发现很多人做了更复杂的事情,但我只需要一个简单的解决方案。这是代码。谢谢!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class emocon extends JFrame implements ItemListener {
JPanel row1 = new JPanel();
JComboBox choose = new JComboBox();
JPanel row2 = new JPanel();
JTextField text = new JTextField(10);
//image will be displayed here
JPanel row3 = new JPanel();
JLabel pic = new JLabel();

//Images
ImageIcon happy = new ImageIcon("images/happy.gif");
ImageIcon lol = new ImageIcon("images/lol.gif");
ImageIcon winky = new ImageIcon("images/winky.gif");
ImageIcon sad = new ImageIcon("images/sad.gif");
ImageIcon worried = new ImageIcon("images/worried.gif");
ImageIcon angry = new ImageIcon("images/angry.gif");
ImageIcon shock = new ImageIcon("images/shock.gif");
ImageIcon uninpressed = new ImageIcon("images/uninpressed.gif");
ImageIcon yawn = new ImageIcon("images/yawn.gif");
ImageIcon evil = new ImageIcon("images/evil.gif");

public emocon(){
    setTitle("Emoticon Converter");
    setSize(350,350);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

GridLayout two = new GridLayout(3,1);
setLayout(two);
 choose.addItem("Happy");
 choose.addItem("LOL");
 choose.addItem("Winky");
 choose.addItem("Sad");
 choose.addItem("Worried");
 choose.addItem("Angry");
 choose.addItem("Shock");
 choose.addItem("Uninpressed");
 choose.addItem("Yawn");
 choose.addItem("Evil");
choose.addItemListener(this);
row1.add(choose);
row2.add(text);
row3.add(pic); 
add(row1);
add(row2);
add(row3);

}
@Override
public void itemStateChanged(ItemEvent item) {
Object source = item.getSource();
String emo = source.toString();
if (emo == "Sad"){
    text.setText("hjgjhg");
}
}   
public static void main(String[] args) {
    emocon emo = new emocon();
}
}

2 个答案:

答案 0 :(得分:3)

你在这里遇到问题:

if (emo == "Sad"){
    text.setText("hjgjhg");
}

不要使用==比较字符串。请改用equals(...)equalsIgnoreCase(...)方法。理解==检查两个对象是否相同而不是您感兴趣的。另一方面,这些方法检查两个字符串是否具有相同顺序的相同字符,并且这才是最重要的。而不是

if (fu == "bar") {
  // do something
}

做,

if ("bar".equals(fu)) {
  // do something
}

,或者

if ("bar".equalsIgnoreCase(fu)) {
  // do something
}

编辑

您的另一个问题是您只是从ItemEvent获取源代码。来源是 JComboBox ,而不是你想要的。您需要获取所选项目!

尝试使用ItemEvent对象中可用的其他方法,而不是getSource()

答案 1 :(得分:1)

获取所选项目:

String item = (String)jComboBox.getSelectedItem();
if(item.equals("Sad")){
    text.setText("hjgjhg");
}