Creating JLabels Dynamically

1

I have to create, from a click of a button, a JLabel dynamically. So that these labels are arranged in an order, giving a name for this JLabel .

The user can create as many labels as he wants ...

How do I do this?

In my action , I have this:

String name = "cor";

    int x = 0;
    int y = 0;
    JLabel label = new JLabel();
    label.setName(name);
    label.setBounds(x, y, 150, 150);

However, it does not add. Where am I going wrong?

    
asked by anonymous 04.07.2016 / 14:52

1 answer

2

Well, I did what follows. By clicking the button, labels are added to the screen.

import java.swing.List;

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class CriaBotoes {

    private final JFrame jf;
    private final List<JLabel> lista;

    public static void main(String[] args) {
        EventQueue.invokeLater(CriaBotoes::new);
    }

    public CriaBotoes() {
        jf = new JFrame("Teste");
        jf.setBounds(10, 10, 700, 700);
        jf.setLayout(null);

        JButton bt = new JButton("Novo label");
        jf.add(bt);
        bt.setBounds(10, 10, 100, 30);

        lista = new ArrayList<>();

        bt.addActionListener(e -> adicionarLabel());
        jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jf.setVisible(true);
    }

    public void adicionarLabel() {
        int n = lista.size() + 1;
        String name = "cor " + n;
        JLabel label = new JLabel(name);
        jf.add(label);
        label.setBounds(10, n * 20 + 20, 150, 20);
        lista.add(label);
    }
}
    
04.07.2016 / 16:05