Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dynamically add JLabels to JPanel?

I'm having a problem with this. I have a JPanel and normally I would create a JLabel like this:

JLabel lblNewLabel = new JLabel("New label");
lblNewLabel.setBounds(0, 0, 135, 14);
panel.add(lblNewLabel);

but I want each time I click a button, in that panel to be created a new JLabel with the same size, but with a different height possition. I tried:

panel.add(new JLabel(stringName));

but this way I don't get to set it's bounds. stringName I get from a JTextField.

like image 468
martin Avatar asked Dec 25 '12 11:12

martin


People also ask

Can you add a JLabel to a JPanel?

Generally JLabel objects are added to JPanel objects.

How are components added to a JPanel?

Use add() to place components in a panel. FlowLayout is the default layout manager for JPanel . Use setLayout() only if you want a different layout manager.

Can you pack a JPanel?

Then the answer to your question is no, there is no other way to do this, the API was designed from the start to make use of the layout managers.


1 Answers

First off, use a layout. Done correctly the layout will place the components like you want. Secondly, when dynamically adding a component to a layout you need to tell the layout to update. Here is an example, it adds a label each time a button is pressed:

public static void main(String[] args) {

    final JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(0, 1));

    frame.add(new JButton(new AbstractAction("Click to add") {
        @Override
        public void actionPerformed(ActionEvent e) {

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    frame.add(new JLabel("Bla"));
                    frame.validate();
                    frame.repaint();
                }
            });
        }
    }));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    SwingUtilities.invokeLater(new Runnable() {
        @Override public void run() {
            frame.setVisible(true);
        }
    });
}
like image 82
dacwe Avatar answered Oct 11 '22 12:10

dacwe