简体   繁体   中英

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. 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.

Now whenether I press the button it prints out a load of garbage regarding the JbUTTON properties. 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

// 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());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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