I have created a JScrollPane with a JPanel inside it and I want to add JPanel/JLabel/Other objects after pressing the button. For example after three button presses I want to get something like this:
I tried myJPane.add(testLabel)
with testlabel.setBounds()
but no result, I don't want to use GridLayout because of the unchangeable sizes. I would like it if the added objects had different sizes - adjusted to the text content.
What should I use for it and how?
Thanks in advance. Best regards, Tom.
I will use a BoxLayout, creating a vertical box, and after each button action, it will add a new JPanel to this box.
Example:
For extra information check on: [https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html]
See also the example [http://www.java2s.com/Code/Java/Swing-JFC/VerticalandhorizontalBoxLayouts.htm]
Here is a
JPanel
inside aJScrollPane
that addsJLabel
s to it when pressing the button:The
BoxLayout
will stack the labels on top of each other.Notes:
setOpaque(true)
must be called onlabel
for it to honor the background color.Box.createRigidArea
is used for creating gaps. Use it as you wish.revalidate()
is imperative in order to display the new components immediately.pack()
(on theJFrame
) will resize it each time to fit all the new components. I just put it there for demonstration since the initial frame size is too small to display the initial components added.Use BoxLayout if you want only add vertically, otherwise you can use FlowLayout for both directions.