Skip to main content

adding multiples buttons and listeners

Please note these forums are being decommissioned and use the new and improved forums at
Posted by onor on August 23, 2011 at 1:49 AM PDT


How can I add multiples buttons(n given by parameter) with text as 1,2...and listeners( just give the number of buttons?

Thank you


Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Re: adding multiples buttons and listeners

import java.awt.FlowLayout;
import java.awt.HeadlessException;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Buttons extends JFrame {

    private JButton button;
    public static final int QUANTITY = 14;
    public static void main(String[] args) {
        new Buttons();

    public Buttons() {
        setLayout(new FlowLayout());


        setSize(400, 400);

    private void createButtons(int quantity) {
        for (int i = 0; i < quantity; i++) {
            button = new JButton("" + i);
            button.addMouseListener(new MouseAdapter() {

                public void mouseReleased(MouseEvent e) {
                    System.out.println(((JButton) e.getSource()).getText());