【问题标题】:How do I make the JButton accept the input from the JTextField? [duplicate]如何让 JButton 接受来自 JTextField 的输入? [复制]
【发布时间】:2016-03-24 06:40:54
【问题描述】:

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

附:忽略未完成的图像代码,我只是想弄清楚如何将单词一起比较

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]);

    }

}

【问题讨论】:

标签: java arrays swing actionlistener string-comparison


【解决方案1】:

使用 .equals 而不是 == 因为您是从“动态”提交的文本创建字符串,因此它不会被分配与您分配时相同的内存:

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

【讨论】:

    【解决方案2】:

    == 比较 object 而不是 string 字面意思。你必须使用.equals

    参考这个

    Java, how to compare Strings with String Arrays

    【讨论】:

      猜你喜欢
      • 2019-01-21
      • 2017-06-11
      • 2014-09-08
      • 2019-12-17
      • 2017-11-10
      • 1970-01-01
      • 2019-07-24
      • 2021-07-15
      • 1970-01-01
      相关资源
      最近更新 更多