基本上,我为字母表中的每个字母创建了一个数组,然后将其添加到 JButtons 数组中。效果很好,但是我现在尝试添加一个动作侦听器,我设法成功地开始工作。
但是,它的工作原理是我有 26 个 if 语句来检查每个按钮是否被按下,因此我尝试添加一个 for 循环。
现在,当我按下按钮时,它会打印出大量关于 JbUTTON 属性的垃圾。我哪里会出错?
String[] letters = { "Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S", "D", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M" };
layout.add(scrollBar);
for (int i=0; i < 26; i++)
{
if (i==25)
{
layout.add(spacebar);
spacebar.setPreferredSize(new Dimension(310,50));
spacebar.setBackground(Color.black);
spacebar.setForeground(Color.white);
spacebar.addActionListener(new action());
}
AlphaButton[i] = new JButton(letters[i]);
AlphaButton[i].setPreferredSize(new Dimension(50,50));
AlphaButton[i].setBackground(Color.black);
AlphaButton[i].setForeground(Color.white);
layout.add(AlphaButton[i]);
AlphaButton[i].addActionListener(new action());
}
class action implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String V = screenArea.getText();
for (int i=0; i < 26; i++)
{
if( e.getSource() == AlphaButton[i] )
{
screenArea.setText(V + AlphaButton[i]);
}
}
}
}