带有actionListener的JButton数组...打印输出结果有问题

时间:2013-11-11 01:19:14

标签: java arrays swing jbutton

基本上我为字母表中的每个字母创建了一个数组,然后将其添加到JButton数组中。这工作正常,但我现在试图添加一个动作监听器,我成功地工作。

但是,它有效,因为我有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]);
                    }
                }

            }
        }

3 个答案:

答案 0 :(得分:2)

如果您需要返回被按下的字母:

screenArea.setText(V + AlphaButton[i].getText);

答案 1 :(得分:0)

您需要覆盖AlphaButton toString方法

// your class
public class AlphaButton {

    @Override
    public String toString() {
        return "This is an AlphaButton";  // or whatever output you want it to say
    }
}

答案 2 :(得分:0)

为什么不简单地做:

public void actionPerformed(ActionEvent e) {
   String V = screenArea.getText();
   screenArea.setText(V + e.getActionCommand());
}