英文:
Setting text of button from an action listener
问题
以下是翻译好的内容:
我在我的代码中有一个 JComboBox
和两个 JButton
控件。
String[] s1 = { "NL", "EN" };
c1 = new JComboBox<>(s1);
c1.setBounds(10, 10, 50, 20);
desgin.startFrame.add(c1);
JButton button = desgin.makeButton(desgin.startFrame, 100, 100, 180, 50, json.getLanguage(languageMenu())[3]);
JButton jButton = desgin.makeButton(desgin.startFrame, 100, 180, 180, 50, json.getLanguage(languageMenu())[4]);
按钮上的语言应该在我更改组合框中的语言时立即改变,但我不知道如何做。我尝试过使用异步:
c1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
JButton button = desgin.makeButton(desgin.startFrame, 100, 100, 180, 50, json.getLanguage(languageMenu())[3]);
JButton jButton = desgin.makeButton(desgin.startFrame, 100, 180, 180, 50, json.getLanguage(languageMenu())[4]);
return null;
}
@Override
protected void done() {
System.out.println("Done");
}
}.execute();
}
});
但这并没有起作用。我做错了什么?
英文:
So I have a JComboBox
and two JButton
controls in my code.
<!-- language-: lang: java -->
String[] s1 = { "NL", "EN"};
c1 = new JComboBox<>(s1);
c1.setBounds(10, 10, 50, 20);
desgin.startFrame.add(c1);
JButton button = desgin.makeButton(desgin.startFrame, 100, 100, 180, 50, json.getLanguage(languageMenu())[3]);
JButton jButton = desgin.makeButton(desgin.startFrame, 100, 180, 180, 50, json.getLanguage(languageMenu())[4]);
The language on the buttons should change the moment I change the language in the combo box, but I have no idea how to do that. I have tried using async:
<!-- language-: lang: java -->
c1.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
JButton button = desgin.makeButton(desgin.startFrame, 100, 100, 180, 50, json.getLanguage(languageMenu())[3]);
JButton jButton = desgin.makeButton(desgin.startFrame, 100, 180, 180, 50, json.getLanguage(languageMenu())[4]);
return null;
}
@Override
protected void done() {
System.out.println("Done");
}
}.execute();
}
});
But it didn't work. What am I doing wrong?
答案1
得分: 0
你可以在 actionListener
内部直接使用 JButton
的 setText()
方法,无需每次都创建新的按钮。
英文:
you can just use 'setText()'
method of JButton
, inside of the actionListener. You should not create new button everytime.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论