BoxLayout ignores subpanel alignment - java

I have a JPanel with a BoxLayout manager that contains subpanels. I want the components inside these subpanels to have a left alignment, but they always appear centered.
It looks like BoxLayout correctly aligns components that are inserted directly, but fails to do that when they are inside a subpanel.
I have modified the example found in http://www.java2s.com/Tutorial/Java/0240__Swing/YAxisAlignment.htm so each button is placed inside a subpanel, and then the subpanel is placed inside the main panel with the BoxLayout manager:
public class YAxisAlignX {
private static Container makeIt(String title, float alignment) {
String labels[] = { "--", "----", "--------", "------------" };
JPanel container = new JPanel();
container.setBorder(BorderFactory.createTitledBorder(title));
BoxLayout layout = new BoxLayout(container, BoxLayout.Y_AXIS);
container.setLayout(layout);
// modified loop. the original version does not create JPanel pan.
// adds the buttons directly the the JPanel container with the
// BoxLayout
for (int i = 0, n = labels.length; i < n; i++) {
JPanel pan = new JPanel();
JButton button = new JButton(labels[i]);
pan.add(button);
button.setAlignmentX(alignment);
pan.setAlignmentX(alignment);
container.add(pan);
}
return container;
}
public static void main(String args[]) {
JFrame frame = new JFrame("Alignment Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container panel1 = makeIt("Left", Component.LEFT_ALIGNMENT);
Container panel2 = makeIt("Center", Component.CENTER_ALIGNMENT);
Container panel3 = makeIt("Right", Component.RIGHT_ALIGNMENT);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout());
contentPane.add(panel1);
contentPane.add(panel2);
contentPane.add(panel3);
frame.pack();
frame.setVisible(true);
}
}
If you execute this version, you can see that the buttons are all centered, despite the alignment set. Why is this happening? Is there any solution? In my case, every subpanel contains several components, and I do not want to add then directly to the main panel.
Thank you very much.

But they are aligned!
First of all, setAlignmentX changes a property at a JComponent level, the layout in which these components are placed may or may not use this information. For example, BoxLayout uses it but FlowLayout and BorderLayout don't.
In your case you are placing some panels with a vertical BoxLayout and you are aligning them in various ways, and it works! It just so happens that the the panels stretch themselves to fit the whole column so actually aligning doesn't change their appearance. You can see this by setting a Border around the panels:
pan.setBorder(BorderFactory.createLineBorder(Color.red));
See:
The fact that the panels contain a button or anything else is mostly irrelevant (it only influences the size that the panel wants to take, and not definitely), the BoxLayout is aligning panels not what is there inside the panels, that's the work of each panel's layout. That's why the buttons wouldn't have its alignment affected by the BoxLayout.
Now how are those buttons deciding its alignment? Well that's up to the layout they are in. The buttons are inside the pan panel that is using the default LayoutManager FlowLayout. Now, as I said, FlowLayout doesn't care for the alignmentX/Y property so the line:
button.setAlignmentX(alignment);
Doesn't accomplish anything. To align in a FlowLayout you need to change its alignment field through FlowLayout.setAligment(int) (docs), you can also do this in the constructor, so If we change the pan declaration to:
JPanel pan = new JPanel(new FlowLayout(FlowLayout.LEFT));
You'll also have the buttons aligned to the left inside their panels:
Of course, all the columns are aligned to the left since the parameter float alignment of makeIt does not influence the FlowLayout's alignment just the BoxLayout's one (and it doesn't matter). You might want to change that argument to an int and call the function with the different FlowLayout constants.
All in all, in the original version the line button.setAlignmentX(alignment); made sense because the buttons were added directly to the container panel and the BoxLayout aligned them properly:
However once you put the buttons inside other panels, the BoxLayout starts aligning the panels (which because of how panels works inside a BoxLayout they were being stretched to fill the whole width) not the buttons, and the buttons alignment is up to the panels layout. That's how it has to work so we can make consistent nested layouts.
I hope that's clear.

Related

BoxLayout inner JPannels alignment - how can I set them to left?

I have been struggling with BoxLayout. I have one JPanel containing 3 inner panels. The external panel is set to BoxLayout with vertical axis, the first and second inner panels were set to set to GridBagLayout and the last one to the flowLayout (left).
The result is that first and second inner containers are aligned to the center(I guess that is is caused by the default behavior of GBL without setting the weightx). How can I align them to the left?
Do I understand correctly that anchor would work inside a cell but not align the whole grid? And that weightx would distribute the space among the cells, but not move the whole container to the left? If that is the true, should I use another component as a wrapper, or is there another way?
panAdv1 = new JPanel();
add(panAdv1);
panAdv1.setLayout(new BoxLayout(panAdv1, BoxLayout.PAGE_AXIS));
// PANEL 1 //
panel1 = new JPanel();
panAdv1.add(panel1);
panel1.setLayout(new GridBagLayout());
....
// PANEL 2 //
panel2 = new JPanel();
panAdv1.add(panel2);
panel2.setLayout(new GridBagLayout());
...
//PANEL 5 - buttons //
panel5 = new JPanel();
panAdv1.add(panel5);
panel5.setLayout(new FlowLayout(FlowLayout.LEFT));
Read the section from the Swing tutorial on Fixing Alignment Problems. The BoxLayout respects the "alignment" property of the component.
How can I align them to the left?
The default for a JPanel would be to have the panel center aligned, so you will need to change the alignment to be left aligned.

basic questions in swing components in Java?

my question is could be very basic in terms of understanding this simple code. I wrote this code myself grabbing bits of code from here and there to understand. I would like to actually follow this code line by line as to what each line means?
I have added my understanding as comments above the line of code, it could be wrong or some of them marked as **** means I just dont know what it means. If you could help me out here, it will be great.
Thanks
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.text.ParseException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class TestingSwingComponents {
public TestingSwingComponents() {
//Create a frame which is the window that pops up
JFrame myframe = new JFrame();
//*****
myframe.getContentPane().setLayout(new BorderLayout());
//set the frame size to be 600 X 600 size
myframe.setSize(600, 600);
// create Pane1
JPanel myPanel = new JPanel();
//set the Layout component of Panel, as how you would like it to be
//here it is 2 rows and 15 columns
myPanel.setLayout(new GridLayout(2, 15));
//create a button with text in it
JButton letterButton = new JButton("click Me");
//add the created button component to the panel
myPanel.add(letterButton);
//******
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
// create another panel
JPanel panelFormat = new JPanel();
//create a textfield
JTextField txtfield = new JTextField();
//create a label for the textfield
JLabel label = new JLabel("Guesss");
//set the layout type for this panel
panelFormat.setLayout(new BorderLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
//I dont know the difference between the below two
//BorderLayout.CENTER still does not center the panel in the frame, I dont know why
myframe.getContentPane().add(panelFormat, BorderLayout.CENTER);
myframe.add(panelFormat);
// default settings
myframe.setTitle("Get buttons");
myframe.setVisible(true);
myframe.setLocationRelativeTo(null);
myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) throws ParseException {
new TestingSwingComponents();
}
}
myframe.getContentPane().setLayout(new BorderLayout());
To answer this, you need to understand the structure of a Swing window. A JFrame (in fact any Swing window) is made up a series of components which generate the view of the window.
(Picture from How to use Root Panes)
A JRootPane makes up the base of view, on-top of which is a JLayeredPane and what is know as the "glass pane". The JLayeredPane is responsible for managing the JMenuBar and the "content pane".
The content pane is where you components reside on the window.
So, what this line is saying is, "get the frame's content pane and set it's layout to use a BorderLayout"
The layouts API is an entire question on it's own and it would be use to you to have a read through Laying out components within a container for a more indeepth description, but basically, layout managers remove the need for you to care (a greate deal) about differences in rendering techniques employeed by different systems...
//******
myframe.getContentPane().add(myPanel, BorderLayout.SOUTH);
This comes back to the layout manager. Because you can have any number of layout managers, Swing allows you to pass a "constraint" to the layout manager when you add the component, giving the layout manager some idea of how you might like this component to be added.
If you take a closer look at BorderLayout you will see that it has five positions in which components can be added.
The line is basically saying, "please add myPanel to the SOUTH position within the frame/content pane"
Update from comments
If you have a look at this snippet...
panelFormat.setLayout(new BorderLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
It sets the layout manager for panelFormat to BorderLayout. BorderLayout can only have a single component in any of it's five available positions. When you use add(Component) without passing it a layout constraint, BorderLayout use CENTER as the default position, this means you are trying to add two components to the CENTER position, this is not possible, so BorderLayout simply uses the last component that was added.
why not borderlayout fix the size of textfield instead of stretching
it all window
Because this is how BorderLayout works and no, GridLayout would probably do something simular.
You could try FlowLayout or GridBagLayout
Updated from comments
You seriously need to take the time to read through the linked (and other suggested) tutorials...but basically, you can use a GridBagLayout just like any other layout, you create an instance of it and apply it to the container...
// create another panel
JPanel panelFormat = new JPanel();
//create a textfield
JTextField txtfield = new JTextField(10);
//create a label for the textfield
JLabel label = new JLabel("Guesss");
//set the layout type for this panel
panelFormat.setLayout(new GridBagLayout());
//add label to panel
panelFormat.add(label);
//add textfield to panel
panelFormat.add(txtfield);
//I dont know the difference between the below two
//BorderLayout.CENTER still does not center the panel in the frame, I dont know why
myframe.getContentPane().add(panelFormat, BorderLayout.CENTER);
myframe.add(panelFormat);
A Swing top-level container, including a JFrame, JDialog is composed of several components all held together including a JRootPane which holds all together, a JLayeredPane, and a contentPane the latter of which holds most of the GUI excepting the top window bar. You can read more about the details in this tutorial here: Top Level Containers:
So when you add a component to a JFrame in a default way, you're actually adding it to its contentPane. In other words, this:
myJFrame.add(myComponent);
is functionally the same as this:
myJFrame.getContentPane().add(myComponent);
For learning Swing, I used this great tutorial which goes over everything you have, and explains it pretty clearly in depth.
The tutorial also goes over the elements that you are having trouble understanding.
Here is said tutorial.

How to set the size of JTextPane according to the size of JPanel?

I want to set the size of the JTextPane according to the size of the panel so that when i add other panels, it changes accordingly. But it just gives a small text pane in the center and when i add some text, it's size changes accordingly.
JPanel panel = new JPanel();
JTextPane txt = new JTextPane();
JScrollPane pane = new JScrollPane();
pane.add(txt);
panel.add(pane,BorderLayout.CENTER);
add(pane);
now the jtextpane just appears at the center of the screen like a small box. I want it to appear according to the size of the panel
JPanel uses FlowLayout by default which sizes components according to their preferred sizes. You can use BorderLayout which will use the maximum area possible.
Also using constraints such as BorderLayout.CENTER has no effect unless the container is actually using BorderLayout. Dont add components to the JScrollPane. This will replaces all components within the view of the component. Instead set the JTextPane as the ViewPortView, for example
JPanel panel = new JPanel(new BorderLayout());
JTextPane txt = new JTextPane();
JScrollPane pane = new JScrollPane(txt);
// pane.add(txt); remove
panel.add(pane, BorderLayout.CENTER);
Read:
How to Use BorderLayout
How to Use Scroll Panes
You added pane twice. Add panel to your base (a JFrame?) instead and remember to actually set your JPanel to use BorderLayout.

How can I split a panel into subpanels?

I already have a panel made (its a row of buttons), and have it located at the bottom of a frame (SOUTH), but I would like to add two rows (panels/ subpanels) beneath it (a text input line and output line if it matters). Right now the only thing I know to do is declare and add more panels, which would be fine, but when I specify .SOUTH they go over top of the previous panel.
EDIT: The solution I used
As suggested by Ted Hopp, I added my original panel (now called subPanel1), as well as the two new panels which were going on top of the original (subPanel2 & subPanel3), to a fourth "container panel" (bottomCotainerPanel). Since I only had three subPanels, this allowed me to specify where in the containerPanel each subPanel would go (using NORTH, CENTER, SOUTH, might have to do something slightly different if you had more than 3...), and then specify where the contianerPanel would go in the frame (SOUTH).
subPanel1.setLayout(new GridLayout(1,6)); //Layout of subPanel1
subPanel1.add(clearButton);
subPanel1.add(customerNameLabel);
subPanel1.add(customerNameTextField);
subPanel1.add(showByNameButton);
subPanel1.add(openNewSavingsButton);
subPanel1.add(openNewCheckingButton);
subPanel2.add(sendChatTextField);
subPanel2.add(sendButton);
subPanel2.add(clearButton2);
subPanel3.add(receiveChatTextField);
subPanel3.add(nextButton);
subPanel3.add(previousButton);
bottomContainerPanel.setLayout(new GridLayout(3,1)); //Layout of Container Panel
bottomContainerPanel.add(subPanel1, BorderLayout.NORTH);
bottomContainerPanel.add(subPanel2, BorderLayout.CENTER);
bottomContainerPanel.add(subPanel3, BorderLayout.SOUTH);
tellerWindow.getContentPane().add(bottomContainerPanel, BorderLayout.SOUTH);
You need to add a single container panel as the SOUTH panel of the frame. The container itself should have the layout that you want for everything that goes at the bottom.
If you just want to split panel onto 2 equal parts at south and north use GridLayout. If you want something in the middle you can use BorderLayout.
If you want to give your user ability to change the sub-panels size use JSplitPane.
I had a similar problem trying to put several rows of buttons into a panel borrowed from the ListDemo example. Well, the first thing to do is to read about BorderLayout: How to Use BorderLayout, or at least see the image shown there:
You cannot have multiple bottom rows in a BorderLayout. But you can use a nested layout. What we need is a BoxLayout, see How to Use BoxLayout:
.
We just have to replace the buttons shown on the above image by rows of buttons.
public class MyStuff extends JPanel {
...
public MyStuff() {
super(new BorderLayout());
...
JPanel buttonArea = new JPanel();
buttonArea.setLayout(new BoxLayout(buttonArea, BoxLayout.PAGE_AXIS));
add(buttonArea, BorderLayout.PAGE_END);
...
//if you dislike the default center alignment:
//panelWithButtons1.setAlignmentX(Component.LEFT_ALIGNMENT);
buttonArea.add(...);// add the 1st panel with buttons
buttonArea.add(...);// add the 2nd panel with buttons
buttonArea.add(...);// add the 3rd panel with buttons

Java Swing Panel Size

Hi I have been learning Java Swing for creating a chess game to practice my Java programming skills.
I've added a JPanel to the east of the JFrame with BorderLayout and I've used the setPrefferedSize(new Dimension(x,y)) method to set the width and height.
After that I have created 4 JPanel and added them with BoxLayout on the previously created panel.
I have tried to set the size of the 4 panels with the setSize(x,y) and setPreferredSize(new Dimension(x,y)) but it dosent work the 4 panels automaticly changed there size to fit the main JPanel and after adding a JLabel on one of them the size of it increased automaticly .
This is my code:
this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
JPanel a = new JPanel();
a.setPreferredSize(new Dimension(50, 50)); //this dosent work
a.add(min);
a.setBackground(Color.red);
this.add;
JPanel b = new JPanel();
b.setBackground(Color.blue);
this.add(b);
JPanel c = new JPanel();
this.add(c);
JPanel d = new JPanel();
d.setBackground(Color.black);
this.add(d);
How can I change the size of each of these panels?
BoxLayout is best for laying out components with varying sizes along a single axis. From the Javadocs:
"BoxLayout attempts to arrange components at their preferred widths (for horizontal layout) or heights (for vertical layout)."
The idea is that they may have different heights (for a horizontal layout) and it will take the maximum height. And, they definitely may have different widths. Also, BoxLayout works with some, er, "interesting" filler pieces like Box.createHorizontalGlue(). These are actually quite useful for flexible, resizeable layouts once you get the hang of it. But, all in all, BoxLayout is for flexible, resizable layout of items with differing sizes.
For simpler cases, especially if you want both preferred width and preferred height to be "respected", use GridLayout as everybody else has suggested.

Categories

Resources