DougBaltazar
DougBaltazar

Reputation: 85

Java getting text of button inside a for

What i need to make to when i click in button, he give me the text inside of the button? Because in this code, if i click button return me ever the last "i" var value... In this case he giving to me "5".

for(int i; i < 5; i++) {
      JButton button = new JButton();
      button.setText("" + i);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) { 
           // TODO add your handling code here:
           System.out.print("\n Test: " + button.getText());

         } 
      });
      button.setSize(60,20);
      button.setLocation(100, 140);
      button.setVisible(true);
      this.add(button);
      this.revalidate();
      this.repaint();
  }

Upvotes: 1

Views: 1921

Answers (2)

kiheru
kiheru

Reputation: 6618

You did not post the original code. As posted it would not compile, so I think button is a field in your class.

The posted code would work with a small modification:

for (int i; i < 5; i++) {
    // Notice the "final"
    final JButton button = new JButton();
    ...

You should likely do this even if you follow Hovercraft's good advice of getting the string from the action event, because the button field is useless.

Getting the string from the action event, you can also reuse one listener for all the buttons:

ActionListener listener = new ActionListener() {
    public void actionPerformed(ActionEvent ae) { 
      System.out.print("\n Test: " + ae.getActionCommand());
    } 
};

for (int i; i < 5; i++) {
    final JButton button = new JButton();
    button.setText(Integer.toString(i));
    button.addActionListener(listener);
    // the rest as before
    ...
}

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285405

Change:

System.out.print("\n Test: " + button.getText());

to

System.out.print("\n Test: " + ae.getActionCommand());

Upvotes: 3

Related Questions