[英]Changing ActionListener to append StringBuilder
Within two statements that have drastically shortened my code I need to add a statement that adds the text of a JButton to a StringBuilder. 在两个大大缩短了我的代码的语句中,我需要添加一条将JButton的文本添加到StringBuilder的语句。 The ActionListener statement exists to disable the JButtons when clicked (a nice aesthetic), but I want to include if possible the ability to append the StringBuilder within the ActionListener as well.
存在ActionListener语句以在单击时禁用JButton(一种很好的美感),但是我想尽可能包括在ActionListener中附加StringBuilder的功能。 The following is the two parts of this code.
以下是此代码的两部分。
theModel.randomLetters();
ActionListener disableButton = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
if (!(event.getSource() instanceof JButton)) {
return;
}
theModel.currentWord.append((JButton)event.getSource());
((JButton)event.getSource()).setEnabled(false);
}
};
for (int i = 0; i < 16; i++) {
JButton dice = new JButton(theModel.letters.get(i));
dice.addActionListener(disableButton);
boggleGrid.add(dice);
}
The .addActionListener(disableButton) adds the above ActionListener to each button when it is produced by the for loop. .addActionListener(disableButton)将上述ActionListener添加到由for循环生成的每个按钮上。 However,
然而,
theModel.currentWord.append((JButton)event.getSource());
is what I thought would properly append the StringBuilder "currentWord" with whatever value the clicked button holds (hence "((JButton)event.getSource())"). 我认为应该将StringBuilder“ currentWord”适当地附加到单击按钮所具有的任何值上(因此为“(((JButton)event.getSource())”))。 There are no errors per say but I have written separate lines of code in my main class to test whether there are any changes to the StringBuilder when any buttons are clicked.
每个发言都没有错误,但是我在主类中编写了单独的代码行,以测试单击任何按钮时StringBuilder是否有任何更改。 There isn't.
没有。
Where and what do I need to do to properly add the value of the clicked JButton to currentWord? 我需要在何处以及如何将单击的JButton的值正确添加到currentWord?
Using (JButton)event.getSource()
will cause the StringBuilder
to invoke the objects toString
method. 使用
(JButton)event.getSource()
将导致StringBuilder
调用对象toString
方法。 This isn't what you want, instead, either use the JButton
's text
property or the ActionEvent
's actionCommand
property, for example... 这不是您想要的,而是使用
JButton
的text
属性或ActionEvent
的actionCommand
属性,例如...
theModel.currentWord.append(((JButton)event.getSource()).getText());
or 要么
theModel.currentWord.append(event.getActionCommand());
instead 代替
Unless you specify the JButton
's actionCommand
yourself, it will use the buttons text as the actionCommand
除非您自己指定
JButton
的actionCommand
,否则它将使用按钮文本作为actionCommand
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.