here's an SSCCE:
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class BoxLayoutTest extends JFrame {
public BoxLayoutTest(){
JPanel main = new JPanel();
main.setLayout(new BoxLayout(main, BoxLayout.Y_AXIS));
main.setBackground(Color.red);
this.add(main);
JPanel northPanel = new JPanel();
JPanel middle = new JPanel();
middle.setLayout(new BoxLayout(middle, BoxLayout.X_AXIS));
middle.add(new JButton("FOO"));
middle.add(Box.createHorizontalGlue());
JPanel aPanel = new JPanel();
aPanel.setBackground(Color.black);
JComboBox b = new JComboBox();
//b.setPreferredSize(new Dimension(100,16)); //uncomment this to see the layout I would like to achieve
//b.setMaximumSize(new Dimension(100,16));
//middle.add(b); //uncomment this line
middle.setBackground(Color.green);
northPanel.setBackground(Color.blue);
main.add(northPanel);
main.add(middle);
main.add(Box.createVerticalGlue());
this.setSize(800,600);
this.setResizable(true);
this.setVisible(true);
}
public static void main(String[] args) {
new BoxLayoutTest();
}
}
I'm trying to refactor some classes I wrote some time ago, when I didn't know that using setXXXSize methods on components is wrong.
Using a resizable frame ,the result I want to achieve is the following:
The northPanel should stay on top and change it's size accordingly to the frame size modifications (seems to work fine)
The green panel where I put the JButton should keep the maximum dimension of the JButton and stay just below the blue panel above (this works fine if I only put JButtons inside that panel).
The problem arise if I put a JComboBox inside the green panel (try to uncomment the line in the SSCCE). I guess JComboBox hasn't a maximum size specified, so it stretches with the frame. In the previous wrong version of my code I was using setxxxSize methods on the JComboBox to limit it's dimension(try to uncomment the line on setXXXSize methods to see it).
My question are:
Is it possible to achieve the same result using BoxLayout without invoking setXXXSize() methods?
If yes, how?
Is there any other LayoutManager that can I use to get that effect?
Please put me in the right direction
JComboBox is misbehaving (the same as JTextField) in reporting an unbounded max height: should never show more than a single line. Remedy is the same: subclass and return a reasonable height
JComboBox b = new JComboBox() {
/**
* #inherited <p>
*/
#Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
just for fun, here's a snippet using MigLayout (which is my personal favorite currently :-)
// two panels as placeholders
JPanel northPanel = new JPanel();
northPanel.setBackground(Color.YELLOW);
JPanel southPanel = new JPanel();
southPanel.setBackground(Color.YELLOW);
// layout with two content columns
LC layoutContraints = new LC().wrapAfter(2)
.debug(1000);
AC columnContraints = new AC()
// first column pref, followed by greedy gap
.size("pref").gap("push")
// second
.size("pref");
// three rows, top/bottom growing, middle pref
AC rowContraints = new AC()
.grow().gap().size("pref").gap().grow();
MigLayout layout = new MigLayout(layoutContraints, columnContraints,
rowContraints);
JPanel main = new JPanel(layout);
main.setBackground(Color.WHITE);
// add top spanning columns and growing
main.add(northPanel, "spanx, grow");
main.add(new JButton("FOO"));
// well-behaved combo: max height == pref height
JComboBox combo = new JComboBox() {
#Override
public Dimension getMaximumSize() {
Dimension max = super.getMaximumSize();
max.height = getPreferredSize().height;
return max;
}
};
// set a prototype to keep it from constantly adjusting
combo.setPrototypeDisplayValue("somethingaslongasIwant");
main.add(combo);
// add top spanning columns and growing
main.add(southPanel, "spanx, grow");
I have always seen using the layout managers in the jdk are not easy. They are either too simple and inflexible or the gridbaglayout is just too much trouble. Instead I started using the jgoodies form layout and never looked back since.. Have a look at it. Its very simple and easy to use. Here's a link:
http://www.jgoodies.com/freeware/forms/
Make sure you go through the white paper.
And now, we also have google providing us a WYSISWG editor for the formlayout as a plugin for eclipse. This just makes life a lot lot easier.
http://code.google.com/javadevtools/wbpro/palettes/swing_palette.html
Related
I have to build a UI with three panels, leftPanel, middlePanel and rightPanel, Panels should be aligned Horizontally
left and right panels should get the maximum and equal width as possible while the middle panel can get the minimum width as its child component required, once the panels are added view should be centered by middle panel.
I have done following test code to build the UI
import java.awt.Color;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class SwingTest extends JFrame {
private static final long serialVersionUID = 1L;
public SwingTest() {
setTitle("Swing Test");
setSize(750, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(getParent());
// Rule used to find the component positions, for the testing purpose
Rule rule = new Rule(Rule.HORIZONTAL, true);
rule.setPreferredWidth(10);
rule.setPreferredHeight(40);
SidePanel leftPanel = new SidePanel("Left");
SidePanel rightPanel = new SidePanel("Right");
JPanel middlePanel = new JPanel();
middlePanel.setBorder(BorderFactory.createLineBorder(Color.black));
// Add left,right and middle panel horizontally
JPanel containerPanel = new JPanel();
containerPanel.setLayout(new BoxLayout(containerPanel, BoxLayout.X_AXIS));
containerPanel.add(leftPanel);
containerPanel.add(middlePanel);
containerPanel.add(rightPanel);
// Add rule and container panel Vertically
JPanel outerPanel = new JPanel();
outerPanel.setLayout(new BoxLayout(outerPanel, BoxLayout.Y_AXIS));
outerPanel.add(rule);
outerPanel.add(containerPanel);
add(outerPanel);
}
public static void main(String[] args) {
SwingTest test = new SwingTest();
test.setVisible(true);
}
private static class SidePanel extends JPanel {
private static final long serialVersionUID = 1L;
private SidePanel(String text) {
setLayout(new GridBagLayout());
add(new JLabel(text));
}
}
}
I have used Rule class from oracle swing tutorial site, it can be used to find the position of components. get Rule.java
The problem i have is as shown in the UI screen shot, view is not get centered by middle panel, Right now the view centered as width of `left + middle panel = right panel'
I don't want to set the panel height and width manually, It should be handled by the LayoutManager itself.
What i want is middle panel has to be get centered in a way left + middle/2 = middle/2 + right panel width.
I couldn't find a way to make the middle panel to get centered to view, Could someone help me to find a solution for this?.
You need to understand how the BoxLayout works.
First space is allocated at the preferred size of each component. Then if there is extra space, that space is allocated to each component.
The middle doesn't appear to be centered because the preferred size of the right label is larger than the left label. So when the extra space is allocated the right side is larger than the left side.
This is easy to test. Just change the text of the right side panel to "LEFT".
However, that leads to another question - Why doesn't the size of the middle panel change? I don't know the answer to this. Although for some reason the default FlowLayout seems to work different than the GridBagLayout. Again you can test this by changing the layout of the middle panel to be a GridBagLayout.
If you always want the left/right panels to be the same size then you might want to consider using the Relative Layout. Using this layout the basic code would be:
RelativeLayout rl = new RelativeLayout(RelativeLayout.X_AXIS);
JPanel panel = new JPanel( rl );
panel.add(leftPanel, new Float(1));
panel.add(middle, new Float(3));
panel.add(rightPanel, new Float(1));
Now the left/right panels will be the same size independent of the components added to each panel.
I am using MigLayout for a very long window.
and I wish to "push" the second and fourth column to fill all the length of the whole window, but I cannot achieve it. There's no push option in column constraint, only grow and fill.
Here's a SCCEE, as someone once suggested, whose name I already forgot:
package com.WindThunderStudio.MigLayoutTest;
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutTest extends JFrame{
private JFrame mainFrame;
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutTest(){
run();
}
public void run(){
mainFrame = new JFrame();
mainFrame.setBounds(0, 0, 1250, 500);
mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JPanel p = new JPanel();
p.setSize(mainFrame.getSize());
p.setLayout(new MigLayout("fill","[max!, grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
mainFrame.setContentPane(p);
panel = new JPanel();
panel.setLayout(new MigLayout("fillx", "[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto);
panel.add(lblResumenAutoResult);
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial);
panel.add(lblResumenRazonSocialResult,"wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo);
panel.add(lblResumenPeriodoResult);
//poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora);
panel.add(lblResumenFechaHoraResult);
p.add(panel,"cell 0 0");
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setBounds(0, 0, 1250, 500);
getContentPane().add(mainFrame.getContentPane());
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutTest test = new MigLayoutTest();
}
});
}
}
If you run the code, you can note that the columns' width increases as its containing text's length changes. But it never fills the whole width of its container.
What's desirable, is to fix the column 0 and 2 by 15% of the whole width, and let column 1 and 3 to ocupy the rest, 35%, with the first two columns occupying the 50% size of the whole width.
Am I missing something here? I don't want to specify the width of every column, setting pre:min:max, because it is bad practice, as suggested by this post, which gets lots of vote up.
panel.setLayout(new MigLayout("fillx",
"[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]",
"[center]10[center]"));
But, if I set pref:min:max, it can fill the whole width.
First the code, then explanation. Try this:
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutTest extends JFrame {
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutTest() {
run();
}
public void run() {
panel = new JPanel();
panel.setLayout(new MigLayout("debug, fill",
"[left, 15%]10[left, 35%]10[left, 15%]10[left, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto, "sg label");
panel.add(lblResumenAutoResult, "sg value");
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial, "sg label");
panel.add(lblResumenRazonSocialResult, "sg value, wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo, "sg label");
panel.add(lblResumenPeriodoResult, "sg value");
// poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora, "sg label");
panel.add(lblResumenFechaHoraResult, "sg value");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
getContentPane().add(panel);
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
MigLayoutTest test = new MigLayoutTest();
}
}
The explanation of my changes:
Now except for simplifying the code and layout I used “debug” within the layout constraints to see what actually happens to the layout. I suggest using it anytime things go wrong with the layout - it makes MigLayout draw the borders of components and cells, thus visualizing potential problems.
I removed the unnecessary mainframe and p - if you really need it for a nested layout try to add it once you have solved the inner layout to your liking.
As to p and panel - it might be that you need here two different layouts, one nested in another, but this is the actual source of your problem. p had also its own grid layout, with
p.add(panel,"cell 0 0");
you put panel in the top left cell of the p - this is why panel was not distributed over the whole window but sat in the upper left corner.
As you see without p it positions nicely in the middle of the screen without any constant size, still showing all components, but more importantly it has 50% of the window size for the first and 50% for the last two columns. This was achieved by giving the components a “sizegroup”:
Gives the component a size group name. All components that share a
size group name will get the same BoundSize (min/preferred/max). It is
used to make sure that all components in the same size group gets the
same min/preferred/max size which is that of the largest component in
the group. An empty name "" can be used.
And it also resizes like it should!
The nested layout might also had been the root of another problem – don’t know if you didn’t notice it or it just didn’t show up on your machine, but if I tried to resize your window the panel got wider and wider (never narrower) even if I shrunk the window. At some point it got wider than the window itself and even then growed further on each resize.
Next - setting the dimensions to a constant value didn’t make sense, since after pack the layout manager starts sizing everything based on preferred sizes of the window and its content. Besides, you never know which size is your users’ screen, so any constant size could be equally bad if effectively used. Better to drive the size through the content and available runtime environment. With your code on my machine it took all available horizontal space of my two screens (2 x 1280) and did’t look pretty.
I also think that you do not need to start the frame using EventQueue.invokeLater, just create a MigLayoutTest and that’s it.
EDIT after OP's own answer
Setting the size using setBounds(0, 0, 1250, 500) before pack is not working correctly (by this I mean making the window be that size). Even in the screenshot below OP's own answer it is not 500px high. Here is what I get on Windows 7 running JDK 1.8.0_91:
The size of my screen is 1280 x 1024, the size of the programm's window is 914 x 301.
I'd suggest using one of the following:
To set it to the constant size of 1250 x 500 px move the setSize between pack and setVisible:
...
pack();
setSize(1250, 500);
I'd use setSize, setBounds doesn't make sense, since by calling setLocationRelativeTo(null) you centering the programm's window on the screen anyway, so the origin is being dismissed immediately.
To maximize horizontally and let the height be 500 px set main window's preferred size before pack:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension(screenSize.width, 500));
And to maximize horizontally and let the preferred height as it was originally:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
setPreferredSize(new Dimension(screenSize.width, getPreferredSize().height));
Of course you can make the window 1250 x 500 big by setting its preferred size instead of using setSize, too.
The resize problem is not so big now, but it's still there - make the window wider, than narrow it just a little bit. You'll notice that the panel gets wider even if the window got narrowed. The problem is that panel component doesn't get big enough to fill the one column of p initially (BTW you can add the 'debug' flag to each MigLayout, also that of the panel - it will then outline all of the inner components as well).
To make it fill the parent container add it like this:
p.add(panel, "cell 0 0, grow");
Now it is the full width of p from the very beginning and resizing works as expected.
Regarding starting the JFrame using invokeLater - we start our main windows usually without it and had never had problems, since there were no interactions with Swing until the first frame was visible, yet I have just noticed that it is regarded to be the best practise - even in Oracle's tutorials. It looks like I had learned something here, too :-).
Comparision of the frame's window with and without adding with "grow"
Test scenario: start the application and resize it to be wider.
As you see in the first screenshot the component size is smaller than the column width - it looks like the component were lying behind the column size while resizing. On the second screenshot the component width remains the same as the column width at all times. As I said previously the reason might be the Java and/or operating system combination, I don't know. But obviously it behaves differently and on my machine less than optimal.
Thanks to #Tomasz Stanczak, I have solved it finally. However, I found part of what he said is relevant, and others are not. For future readers who may see this, I have to made it clearer.
The final working code is:
import java.awt.Cursor;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class MigLayoutMySCCEE extends JFrame{
private JFrame mainFrame;
private JPanel panel;
private JLabel lblResumenAuto;
private JLabel lblResumenAutoResult;
private JLabel lblResumenRazonSocial;
private JLabel lblResumenRazonSocialResult;
private JLabel lblResumenPeriodo;
private JLabel lblResumenPeriodoResult;
private JLabel lblResumenFechaHora;
private JLabel lblResumenFechaHoraResult;
public MigLayoutMySCCEE(){
run();
}
public void run(){
JPanel p = new JPanel();
p.setLayout(new MigLayout("debug, fill","[grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
panel = new JPanel();
panel.setLayout(new MigLayout("fillx", "[left, 15%]10[left, grow, 35%]10[left, 15%]10[left, grow, 35%]", "[center]10[center]"));
lblResumenAuto = new JLabel("MY LABEL 1111111111111");
lblResumenAutoResult = new JLabel("1111111111111111111111");
panel.add(lblResumenAuto);
panel.add(lblResumenAutoResult);
lblResumenRazonSocial = new JLabel("MY LABEL 2222222222");
lblResumenRazonSocialResult = new JLabel("2222222222222222222222");
panel.add(lblResumenRazonSocial);
panel.add(lblResumenRazonSocialResult,"wrap");
lblResumenPeriodo = new JLabel("MY LABEL 33333333333333");
lblResumenPeriodoResult = new JLabel("3333333333333333333333333333333333333333333333333333333");
panel.add(lblResumenPeriodo);
panel.add(lblResumenPeriodoResult);
//poner el texto como html puede tener otra linea, porque es muy largo
lblResumenFechaHora = new JLabel("<html>MY LABEL <br /> 4444444444444444</html>");
lblResumenFechaHoraResult = new JLabel("4444444444444444444444444");
panel.add(lblResumenFechaHora);
panel.add(lblResumenFechaHoraResult);
p.add(panel,"cell 0 0");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setBounds(0, 0, 1250, 500);
getContentPane().add(p);
pack();
setVisible(true);
setLocationRelativeTo(null);
setResizable(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutMySCCEE test = new MigLayoutMySCCEE();
}
});
}
}
And the window looks like:
Some notes:
The debug trick is very useful and urges me to read DOC again. I wish it can gain more attention and importance in the Quick Start page, however.
The unnecessary nesting is a problem and Tomasz make me to review the hierarchy, great! I changed the nesting part to make it clearer. But it's irrelevant.
The sizeGroup part is great idea and I decide to use it in future development as much as possible, but it's irrelevant to my case. I solved it without using it.
I have found the wider-and-wider problem after Tomasz's tip, but it is due to [max!] combined with adding the panel to the first cell of grid layout, not frame/panel nesting. I removed [max!] and changed it to [grow] and the width is not expanding anymore. I didn't touch the p.add(panel, "cell 0 0") part. As observed and by definition,
p.setLayout(new MigLayout("debug, fill","[grow]","[50:20:30]10[100::]10[20::]10[50!]10[20!]"));
the first line of the panel has only one column, if I understand well.
EDIT after Tomasz's edit
I surely have learned more than you did :) I tried to get rid of setBounds() part and to change add(panel, "cell 0 0") to add(panel, "grow"), but I cannot see much difference, am I missing something here? Yet "grow" is almost always the better choice and desirable.
Here's 2 GIFs showing what I got: (by ScreenToGif, a light-weighted but powerful tool, especially useful for showcase)
edit: if you downvote this question, you may leave a comment to explain why, that will be more constructive.
I obtain this unexpected result...
... using this code:
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestAlignment extends JFrame {
// Constructor
public TestAlignment() {
super("Test Alignment");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Components to show
JLabel leftLabel = new JLabel("Left");
JButton centerButton = new JButton("Middle");
JLabel rightLabel = new JLabel("Right");
// Add all to box
Box box = Box.createVerticalBox();
box.add(leftLabel);
box.add(centerButton);
box.add(rightLabel);
box.add(Box.createHorizontalStrut(180));
// Align content in box
leftLabel.setAlignmentX(LEFT_ALIGNMENT);
centerButton.setAlignmentX(CENTER_ALIGNMENT);
rightLabel.setAlignmentX(RIGHT_ALIGNMENT);
// Add box to frame, and show frame
box.setOpaque(true);
setContentPane(box);
setVisible(true);
}
// Main
public static void main(String[] args) {
// Create frame in EDT
SwingUtilities.invokeLater(new Runnable() {
#Override public void run() { new TestAlignment(); }
});
}
}
I understand now this works as expected for JComponent.setAlignmentX(): this method tells which sides of the components must be aligned (top label leftmost side aligned with button center and bottom label rightmost side).
I would like to understand how to have each label aligned as expected intuitively (left label on the left, right label on the right), labels touching the vertical edges of the Box?
(I know how to do with putting each label in a Box embedded, and using Box.createHorizontalGlue() to force it to the left or the right side, but seems to me too much for the simple purpose of alignment. I'm looking for something more simple)
Don't think you can do this with a BoxLayout. Your example does show the intuitive code, which doesn't work as you would hope.
I would suggest you probably need to use a GridBagLayout. I think it supports the setAlignmentX(...) method the way you want to use it.
If not, then can use the Relative Layout. It is simple to use, like the BoxLayout and does support the alignment you want when you use:
setAlignment( RelativeLayout.COMPONENT );
You can use BoxLyout:
// Components to show
// Left
JLabel leftLabel = new JLabel("Left");
JPanel leftPanel = new JPanel();
leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.X_AXIS));
leftPanel.add(leftLabel);
leftPanel.add(Box.createHorizontalGlue());
// Center
JButton centerButton = new JButton("Middle");
// Right
JLabel rightLabel = new JLabel("Right");
JPanel rightPanel = new JPanel();
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.X_AXIS));
rightPanel.add(Box.createHorizontalGlue());
rightPanel.add(rightLabel);
// Add all to box
Box box = Box.createVerticalBox();
box.add(leftPanel);
box.add(centerButton);
box.add(rightPanel);
box.add(Box.createHorizontalStrut(180));
// Align content in box
// leftLabel.setAlignmentX(LEFT_ALIGNMENT);
centerButton.setAlignmentX(CENTER_ALIGNMENT);
// rightLabel.setAlignmentX(RIGHT_ALIGNMENT);
So I am a computer science student and I've finished my first year. I wanted to create a simple program and I realized that I am so tired of using no layout;
this.setLayout(null);
It is so tiresome to add bounds to every single component. Well, I have been using JPanel components and GridLayout a lot, which have made my work a bit easier. But I am tired of it.
I care very much about the look of the GUI I make and use almost half the time programming to make the GUI look good before I start adding the functionality of the code. By not using a layout and adding bounds I am forced to setResizable(false) because it looks bad if I change the size of the JFrame.
I've been searching a bit, and I know of BorderLayout, and FlowLayout, but I don't like them. Is there any Layout that keeps the relative size of the components with respect to the size of the window?
For example I want to make a simple program that looks like this: (Quick sketch in Photoshop)
I can easily make this with 3 panels, but as I said, if I change the size of the frame everything stays in place instead of being relative to the window-size.
Can you guys help me?
This design looks for me to fit the BorderLayout, where in the NORTH you have the values that changes the CENTER you have the main part, and the SOUTH you have the buttons.
Link to the Oracle Border Layout
You can apply this BorderLayout to the JFrame, then create 3 JPanels for each of the NORTH,CENTER and SOUTH sections. If you want to use responsive design for the components and panels, take a look at GridBagLayout which is much more flexible than the GridLayout
Layout management is a very complex problem, I don't think people really appreciate just how complex it really is.
No one layout is ever going to achieve everything your want, in most cases, you will need to resort to two or more layouts, especially as your requirements become more complex.
For example, the following is simply a BorderLayout at the base and the buttons on a JPanel using a FlowLayout
Which is achieved by using
JList listOfThings = new JList(...);
JTextField tf = new JTextField();
JButton add = new JButton("Add");
JButton delete = new JButton("Delete");
JButton go = new JButton("Go...");
JPanel buttons = new JPanel();
buttons.add(add);
buttons.add(delete);
buttons.add(go);
add(new BorderLayout());
add(tf, BorderLayout.NORTH);
add(new JScrollPane(listOfThings));
add(buttons, BorderLayout.SOUTH);
For more complex layouts, I would consider using something like GridBagLayout. You may also want to consider MigLayout as an alternative
Take a look at Laying Out Components Within a Container for more details about using layout managers
I'd like to use the combination of BorderLayout and BoxLayout. BorderLayout let me put the component based on their relative location's relation and BoxLayout let me manage the subtle distance ( create some white space). You can use component.setBorder(BorderFactory.createEmptyBorder(top, left, bottom, right)); to achieve this goal too.
Here is a demo and hope it can help you.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class LayoutTest{
private JTextField jTextField;
public void createUI(){
JFrame frame = new JFrame("Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.add(new TextFieldPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ListPanel());
mainPanel.add(Box.createVerticalStrut(8));
mainPanel.add(new ButtonPanel());
frame.add(mainPanel,BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
LayoutTest layoutTest = new LayoutTest();
layoutTest.createUI();
}
#SuppressWarnings("serial")
class TextFieldPanel extends JPanel{
public TextFieldPanel(){
setLayout(new BorderLayout());
jTextField = new JTextField();
jTextField.setEditable(false);
add(jTextField,BorderLayout.CENTER);
}
}
#SuppressWarnings("serial")
class ListPanel extends JPanel implements ListSelectionListener{
private JList<String> list;
public ListPanel(){
setLayout(new BorderLayout());
String stringArr[] = new String[30];
for (int i = 0; i < 30; i++) {
stringArr[i] = "JList :This line is item" + i;
}
list = new JList<String>(stringArr);
JScrollPane scrollPane = new JScrollPane(list);
add(scrollPane,BorderLayout.CENTER);
setBackground(new Color(211,211,211));
list.addListSelectionListener(this);
}
#Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
jTextField.setText(list.getSelectedValue());
}
}
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BorderLayout());
add(button1,BorderLayout.WEST);
add(button2,BorderLayout.CENTER);
add(button3,BorderLayout.EAST);
}
}
}
Here is the effect:
You can use BoxLayout for ButtonPanel if you don't want to let the button's size change.
#SuppressWarnings("serial")
class ButtonPanel extends JPanel{
public ButtonPanel(){
JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
add(button1);
add(Box.createHorizontalStrut(8));
add(button2);
add(Box.createHorizontalStrut(8));
add(button3);
}
}
And the effect is like this:
For more infomation about using BoxLayout to generate whitespace, you can refer to https://stackoverflow.com/a/22525005/3378204
Try GridBagLayout.
Your sketch is actually quite close to the one of the examples in the official tutorial.
HVLayout keeps the relative size of the components with respect to the size of the window, that is, if you configure components to have a relative size (e.g. buttons usually do not grow or shrink - they stick to their preferred size). This SO question was one of the motivations for me to push HVLayout to a release and a screenshot is included (showing big window size, smalll size and preferred "default" size):
Source code for the window is in RelativeToWindowSize.java
A number of helper-classes from HVLayout are used to build the window, so I don't think it will be of much use here, but to get an impression, the "build window" part shown below:
public RelativeToWindowSize build() {
CSize cs = new CSize();
CForm form = new CForm(new VBox(new Insets(2, 4, 2, 4)), cs);
addTitledBorder(form.get(), "Vertical box", Color.BLACK);
form.add(new JScrollPane(
tfield = new JTextArea("Value that changes with value choosen from list.\nhttp://stackoverflow.com/questions/24462297/layout-relative-to-screensize/")
)).csize().setAreaSize(1.0f, 2.5f).fixedMinHeight().setMaxHeight(4.0f);
// tfield shows mono-spaced font by default.
tfield.setFont(SwingUtils.getUIFont());
form.add(new JScrollPane(vlist = new JList<String>(getListValues())))
.csize().setAreaSize(1.0f, 5.0f);
form.addChild(new HBox());
addTitledBorder(form.get(), "Horizontal box", Color.RED);
form.addChild(new HBox(SwingConstants.CENTER));
addTitledBorder(form.get(), "Centered box.", Color.BLUE);
form.add(createButton(cs, "Add"));
form.add(createButton(cs, "Modify"));
form.up();
form.addChild(new HBox(SwingConstants.TRAILING));
addTitledBorder(form.get(), "Trailing box", Color.GREEN);
form.add(createButton(cs, "Delete"));
setContentPane(form.getRoot());
pack();
setLocationByPlatform(true);
//applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
vlist.addListSelectionListener(this);
log.debug(getClass().getName() + " build.");
return this;
}
private Component createButton(CSize cs, String text) {
// For purpose of demo, let button shrink in width.
return cs.set(new TButton(text)).setFixed().shrinkWidth(0.33f).get();
}
I am creating an interface in java and i want to align the button to the right. I have try but its not working. Can someone tell me how to do it?
import java.awt.Color;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Button_Alignment extends JFrame{
public JPanel header,body,footer;
public JButton add1;
public JButton save;
public Button_Alignment(){
super("BUTTON");
GridLayout g1 = new GridLayout(3,1);
setLayout(g1);
//////
header = new JPanel();
JButton add1 = new JButton("add");
header.add(add1);
JButton save = new JButton("save");
header.add(save);
//////
add(header);
header.setBackground(Color.cyan);
}
public static void main(String[] args){
Button_Alignment ba = new Button_Alignment();
ba.setSize(400, 400);
ba.setVisible(true);
}
}
Your current layout manager (GridLayout) is being created with 3 rows and a single column. Hence, the components you add to the JFrame will appear vertically from top to bottom. Worse still, GridLayout will aportion space equally amongst all 3 components, meaning that your buttons will stretch in both directions, which is almost certainly not what you require.
I would consider using an alternative layout manager. For simple layouts I tend to favour BorderLayout or FlowLayout. For more complex layouts I lean towards GridBagLayout although there are others who prefer MigLayout.
More information here.
Try like this:
JButton save = new JButton ("save");
setLayout (new BorderLayout ());
add (save, BorderLayout.EAST);
you set GridLayout to the JFrame constructor instead of JPanel (JPanel has by default FlowLayout), I think that
header.setLayout(new GridLayout(3,1));
header.add(add1);
header.add(save);
notice ---> but GridLayout in current ComponentOrientations to start from left to right, then 3rd. grid is empty
then only to add JFrame#add(JPanel), in your case
add(header);
A quick and dirty way is to put the button [or a container immediatly wrapping the button, if you want to add other components on the right next to your button] it in a container that uses the BorderLayout and use the BorderLayout.EAST layout constraint for that button [or wrapping container].