[英](Java) Creating multiple(26) buttons with ActionListeners without repeating code
I'm creating a program with a button for each letter of the alphabet. 我正在为每个字母创建一个带有按钮的程序。 When clicked, a word is shown in one JLabel and an image in another.
单击时,一个单词将显示在一个JLabel中,而一个图像则显示在另一个JLabel中。 The word is also stored in a list.
该单词也存储在列表中。 I'm wondering if there's a way to do this without repeating a block similar to this 26 times.
我想知道是否有一种方法可以重复26次类似的代码块。
JButton btnA = new JButton("A");
btnA.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
lblImages.setText("");
lblImages.setIcon(newImageIcon(image);
lblWord.setText("Apple");
words.add(lblWord.getText());
}
});
btnA.setFocusable(false);
panel.add(btnA);
Start by defining a reusable ActionListener
. 首先定义一个可重用的
ActionListener
。 To make it easier, I'm also using a "word" delegate, which will actually perform the required functionality instead of exposing a bunch of components to the ActionListener
为了简化操作,我还使用了“单词”委托,该委托实际上将执行所需的功能,而不是将大量组件暴露给
ActionListener
WordActionListener
public class WordActionListener implements ActionListener {
private String word;
private WordListener listener
public WordActionListener(String work, WordListener listener) {
this.word = word;
this.listener = listener;
}
public void actionPerformed(ActionEvent e) {
listener.addWord(word);
}
}
WordListener
public interface WordListener {
public void addWord(String word);
}
Your UI, which is been used to display the content will need to implement the WordListener
interface 您的用于显示内容的UI需要实现
WordListener
接口
public class ... extends ... implements WordListener {
//...
public void addWord(String word) {
lblImages.setText("");
lblImages.setIcon(newImageIcon(image);
lblWord.setText("Apple");
words.add(lblWord.getText());
}
}
When constructing your buttons, you will need a list of words... 构造按钮时,您将需要一个单词列表...
private String[] listOfWords = String[] {"Apple", ..., "Zebra"};
Then you can just loop over them... 然后,您可以循环播放它们...
for (char c = 'A'; c <= 'Z'; c++) {
JButton btn = new JButton(Character.toString(c));
btn.addActionListener(new WordActionListener(listOfWords[c - 'A'], this);
btn.setFocusable(false);
panel.add(btn);
}
or some such thing 或类似的东西
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.