Pedro Nunes
Pedro Nunes

Reputation: 412

Using a function to create multiple components and change line automatically [Java]

So i lost some hours already with this and i can't seem to find a solution.

Basically i have a Jframe and inside, i have a Scrollpane and a panel I have 1 Jlabel, 1 JTextField and 1 JButton inside that panel in a single line. The JButton can add a new JLabel, a new JTextField and a new JButton, but i can't get them to be positioned in the next line.

I have been messing around with the layouts, but none of them fits my needs, and unfortunaly i never understand or learned how the GUI of java Works.

How's the best way to just keep adding those componentes (Jlabel, Jtextfields and Jbuttons) on a next line for every click i made?

This is my code:

private void BtnaddvariableActionPerformed(java.awt.event.ActionEvent evt) {                                               
        JLabel Lblvariablextra = new JLabel("Testing");
        PanelVariable.add(Lblvariablextra);
        ScrollPaneVariable.setViewportView(PanelVariable);
}   

The code only contains an exemple of the label tough.

Upvotes: 0

Views: 159

Answers (1)

camickr
camickr

Reputation: 324147

Create a main panel that is added to the scroll pane when the GUI is created:

Box main = Box.createVerticalBox();
scrollPane.setViewportView( main );

Then in the ActionListener you create a child panel contain the 3 components every time the button is pressed:

JPanel child = new JPanel();
child.add( new JLabel("I'm a label") );
child.add( new JTextField(10) );
child.add( new JButton("Click Me") );
main.add(child);

Read the section from the Swing tutorial on Layout Manager to understand how layout management works.

Upvotes: 1

Related Questions