MultiButt.java 1.43 KB
package tp2.getSource;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class MultiButt extends JFrame {

    private final JLabel label;
    private final int nbButtons = 3;

    public MultiButt() throws HeadlessException {
        super();
        this.setLocationRelativeTo(null);
        BoxLayout layout = new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS);
        this.setLayout(layout);

        this.label = new JLabel(" ");
        label.setFont(new Font("SansSerif", Font.PLAIN, 25));

        JPanel topPanel = new JPanel();
        topPanel.add(label);
        this.add(topPanel);

        ActionListener listener = new ClicListener();

        for (int i = 0;i < nbButtons; ++i){
            JPanel tmp = new JPanel();
            JButton butt = new JButton("Bouton "+ i);
            butt.addActionListener(listener);
            tmp.add(butt);
            this.add(tmp);
        }

        this.setResizable(false);
        this.pack();

        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }

    private class ClicListener implements ActionListener {

        public ClicListener() {
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            label.setText(((JButton) e.getSource()).getText());
        }
    }

    public static void main(String[] args) {
        new MultiButt();
    }
}