CodeBoy CodeBoy - 1 year ago 73
Java Question

Looping to make JButtons that hold their name values

EDIT: The answer to the button generating part of this question can be found here:
Array that Holds JButton Objects

I used a for loop to generate some JButtons each labeled with their index. Within the loop, I attach an ActionListener to each button. The listener retrieves the label of the button and prints it. Currently, the only button which returns a value is the last one created, which makes sense. I'm wondering if there is a way to do this sort of mass-generation and then individual retrieval in an advantageous way.


Make a bunch of labeled JButtons in a loop.
Print the label when a button is clicked.

Here is a short, executable example of what my current process looks like:

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.setLayout(new FlowLayout());
mainFrame.setSize(250, 300);
mainPanel.setLayout(new FlowLayout());

class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
System.out.println(((JButton) e.getSource()).getText());

Answer Source

You can create an array of buttons, for example:

JButton[] btns = new JButtons[10];
for(int x=0; x<btns.length; x++)
    btns[x] = new JButton(x + "");

Create your ActionListener:

private class ButtonHandler() implements ActionListener{
    public void actionPerformed(ActionEvent e){
        System.out.println( ((JButton)e.getSource()).getText() );

Add each button to the ActionListener:

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

When you click any of the buttons, it will trigger the ActionListener and based on the button that was clicked, print the text from the JButton to the console.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download