Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

I want to have a bunch of labeled JButtons in a loop to print the label when a button is clicked. Below is the code I’ve written so far: 

import java.awt.FlowLayout;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.JButton;

public class calc {

private JFrame mainFrame;

private JPanel mainPanel;

private JButton button;

public calc(){

    mainFrame = new JFrame("Calculator");

    mainPanel = new JPanel();

    for (int i=0; i<10; i++){

        int value = i;

        String number = Integer.toString(value);

        button = new JButton(number);

        button.addActionListener(new ButtonListener());

        mainFrame.add(button);

    }

    mainFrame.setLayout(new FlowLayout());

    mainFrame.setSize(250, 300);

    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(mainPanel);

    mainFrame.setVisible(true);

}

class ButtonListener implements ActionListener {

      @Override

      public void actionPerformed(ActionEvent e) {

          if (e.getSource() == button) {

           System.out.println(((JButton) e.getSource()).getText());

          }

      }

   }

}

Can anyone tell me how to do this?

1 Answer

0 votes
by (19.7k points)

To create an array of button, check the code below:

JButton[] btns = new JButtons[10];

for(int x=0; x<btns.length; x++)

    btns[x] = new JButton(x + "");

To create the ActionListener:

private class ButtonHandler implements ActionListener{

    @Override

    public void actionPerformed(ActionEvent e){

        System.out.println( ((JButton)e.getSource()).getText() );

    }

}

Now to add each button to the ActionListener:

ButtonHandler handler = new ButtonHandler();

for(int x=0=; x<btns.length; x++)

    btns[x].addActionListener(handler);

Interested in Java? Check out this Java tutorial by Intellipaat.  

Browse Categories

...