简体   繁体   English

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

[英]JButton Array with actionListener…trouble printing out result

Basically I've made a array for each letter of the alphabet and then added it to a array of JButtons. 基本上我已经为字母表的每个字母创建了一个数组,然后将它添加到JButton数组中。 That works fine however I've now attempted to add on a action listener which I managed to succesfully get working. 这工作正常,但我现在尝试添加一个动作监听器,我成功地工作。

BUT, it works as I have 26 if statements to check if each button is pressed hence why I've tried adding a for loop. 但是,它有效,因为我有26个if语句来检查每个按钮是否被按下因此为什么我尝试添加for循环。

Now whenether I press the button it prints out a load of garbage regarding the JbUTTON properties. 现在我按下按钮,打印出关于JbUTTON属性的大量垃圾。 Where could I be going wrong? 我哪里可能出错?

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]);
                    }
                }

            }
        }

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

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

You need to override the AlphaButton toString method 您需要覆盖AlphaButton toString方法

// your class
public class AlphaButton {

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

Why not simply do: 为什么不简单地做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM