0

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

            }
        }

3 Answers 3

2

If you need to return the letter that was pressed:

screenArea.setText(V + AlphaButton[i].getText);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 now I think about it, this seems like the more appropriate simplest answer OP is looking for.
0

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

Comments

0

Why not simply do:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.