Skip to main content

adding multiples buttons and listeners

1 reply [Last post]
onor
Offline
Joined: 2011-08-23
Points: 0

Hello,

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.
ellephunk
Offline
Joined: 2011-08-23
Points: 0

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() {
        super("Buttons");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout());

        createButtons(QUANTITY);

        setSize(400, 400);
        setVisible(true);
    }

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

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

            add(button);
        }
    }
}