Omar Qassem
Omar Qassem

Reputation: 107

How to dynamically add jPanels to a JScrollPane that has been added to the JFrame using NetBeans GUI creator?

This may be a silly question, and I'd rather not use the NetBeans inbuilt GUI editor, but I've been asked to.

The problem I'm having is I'm attempting to add a JPanel (itself containing a few labels) to an already existing JScrollPane that is on a JFrame. The JScrollPane and JFrame have been created using the NetBeans GUI editor.

I have an ArrayList (of undetermined size) of orders, and for each order in the ArrayList I'm attempting to create a JPanel and put it in the JScrollPane.

I'm having trouble with adding a JPanel to a JScrollPane and then adding labels to the JPanel. I've looked at tutorials online but all of them need reference to the JFrame... but because I'm using the inbuilt GUI editor that comes with NetBeans I can't reference the JFrame in the code.

The code I'm currently using:

    FlowLayout experimentLayout = new FlowLayout(FlowLayout.CENTER);
    JPanel panel = new JPanel();
    panel.setLayout(experimentLayout);
    JPanel panel2 = new JPanel();
    JLabel label2 = new JLabel("Hello");
    scrollPane.add(panel); //ScrollPane is already on form (put there by GUI editor)
    panel.add(panel2);
    panel2.add(label2);

Any help on how to add these JPanel to the JScrollPane would be very much appreciated!

Upvotes: 3

Views: 7954

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347194

With out the code, it's impossible to be 100% sure, but you would do it like you would had you built the UI yourself.

jScrollPane1.setViewportView(yourPanel);

If you don't have direct access to the internals of the frame, then you need to provide some sort of access methods to allow you to do so.

Upvotes: 5

Omar Qassem
Omar Qassem

Reputation: 107

I've figured it out! I used the scrollPane.getViewport().add(panel); instead of just .add :)

Thanks for your help :)

Upvotes: 4

Related Questions