如何让JButton接受来自JTextField的输入?

时间:2016-03-24 06:40:55

标签: java arrays swing actionlistener string-comparison

我试图创建一个程序,将英语单词翻译成日语,反之亦然,这些程序列在给定的数组中。它还将显示给定单词的图像。对于我的actionPerformed方法,我把它编码为"英语到日语"按下按钮,for循环将一直运行,直到JTextField的输入与englishWords数组中列出的单词相同。但我不确定这是否正确。是我的for循环不正确还是我接近代码错了?

P.S。忽略未完成的图像代码,我只想弄清楚如何比较单词

public class Translator extends JApplet implements ActionListener
{

//English array
String[] englishWords = { "Fish", "Lettuce", "Bike", "Chef", "Teacher" };    

//Japanese array
String[] japaneseWords = { "Sakana", "Retasu", "Jitensha", "Shefu", "Sensei" };

//Image array
Image[] wordImages;
Image wrong;

//Java util
JButton english, japanese;
ImageIcon icon;
JLabel label;
JTextField words;

public void init()
{

    //Images
    wordImages = new Image[5];
    wordImages[0] = getImage(getCodeBase(), "Fish.jpg");
    wordImages[1] = getImage(getCodeBase(), "Lettuce.jpg");
    wordImages[2] = getImage(getCodeBase(), "Bike.jpg");
    wordImages[3] = getImage(getCodeBase(), "Chef.jpg");
    wordImages[4] = getImage(getCodeBase(), "Sensei.jpg");
    wrong = getImage(getCodeBase(), "Wrong.jpg");

    //Layout
    setLayout(new FlowLayout());
    words = new JTextField(null, 10);
    english = new JButton("English to Japanese");
    japanese = new JButton("Japanese to English");
    icon = new ImageIcon(wordImages[0]);
    label = new JLabel( icon, JLabel.CENTER);
    icon.setImage(wordImages[0]);
    label.setIcon(icon);

    //ActionListener
    english.addActionListener(this);
    japanese.addActionListener(this);

    //Install
    add(words);
    add(english);
    add(japanese);
    add(label);
}
public void actionPerformed( ActionEvent ae )
{
    Object src = ae.getSource();
    if(src == english)
    {
        for(int x = 0; x < englishWords.length; ++x)
            if(englishWords[x] == words.getText())
            icon.setImage(wordImages[x]);
    }
    else if(src == japanese)
    {
        for(int x = 0; x < japaneseWords.length; ++x)
            if(japaneseWords[x] == words.getText())
                icon.setImage(wordImages[x]);

    }

}

2 个答案:

答案 0 :(得分:-1)

使用.equals而不是==因为您正在从文本字段创建字符串&#34;动态&#34;因此,当你这样做时,它不会被分配相同的内存:

String s1 = "Fish";
String s2="Fish"l

答案 1 :(得分:-1)

==从字面上比较object而不是string。您必须使用.equals

参考此

Java, how to compare Strings with String Arrays