Reputation: 59
I am making a GUI that works in this way:
Is like a stack of elements. I enter one elemente in my stack and I want to be in the center of my JPanel (that is inside of a JScrollPane). The next element that I add need to be in the center, and the last element, goes X to the left. I add a new element and occurs the same. When an element are out of the JPanel, the JScrollPane need to activate and let me to Scroll to the left to see all.
JPanel a = new JPanel();
this.setBackground(new java.awt.Color(200, 200, 200));
this.setPreferredSize(new java.awt.Dimension(father.getSize().width, height));
BoxLayout aaa = new BoxLayout(this,1);
this.setLayout(aaa);
FlowLayout MigasDePanLayout = new FlowLayout(0,80,0); //Este es la separacion entre elementos
a.setLayout(MigasDePanLayout);
JButton ab = null;
sp = new JScrollPane(a);
sp.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);
sp.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
sp.setBounds(0, 0,father.getSize().width, height);
this.add(sp);
father.add(this, java.awt.BorderLayout.PAGE_END);
for (int i = 0; i < 20; i++) {
ab = new JButton("HHH");
ab.setLocation(i*20, 0);
a.add(ab);
}
addMouseListener(this);
addMouseMotionListener(this);
}
I have this code (Father is a JPanel).
I use a Layout to get the separation of each element, but when I add a new element, always is set on the first hole starting from the left
[][][]
I add a new element
[A][][]
I want this:
[][A][]
Or this, but puting the element in the center of the view:
[][][A] --> []|[][A][]
But I dont know if I can choose where I want to put the element.
I read that is necessary delete the layout to be free and you can to put the element (the button in this case) in a position X Y.
Someone knows if there is any way to put the element in the position that I want? (is something lie that insert from right to left instead left to right, but centering the element)
I need to delete the layout or create another component to achieve my objective?
Thanks for your time!
Upvotes: 1
Views: 520
Reputation: 324078
But I dont know if I can choose where I want to put the element.
You can use:
panel.add(component, index);
to insert the component at a specific position. Most layout managers, like BoxLayout, FlowLayout and GridLayout, that don't use constraints will respect this parameter.
int count = panel.getComponentCount();
So the value of the index must be less than the count.
(is something lie that insert from right to left instead left to right, but centering the element)
So when using a FlowLayout with center alignment all you need is:
panel.add(component, 0);
Also, don't use code like the following:
ab.setLocation(i*20, 0);
It is confusing as it will be ignored because the layout manager will set the location and size.
Upvotes: 3