Java GridBagLayout - disable vertical fill - java

I'm having a problem with vertical filling in my GridBagLayout-GUI. Here is the Code:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class Spielklasse {
public static void main(String[] args) {
JPanel page = new JPanel();
page.setLayout(new GridBagLayout());
for (int i = 0; i < 5; i++) {
JPanel subPanel = new JPanel(new BorderLayout());
JLabel label = new JLabel();
label.setText("label " + i + ":");
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(120,20));
subPanel.add(label, BorderLayout.WEST);
subPanel.add(textField, BorderLayout.EAST);
GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.NORTHWEST;
c.gridx = 1;
c.gridy = i;
c.weightx = 1;
c.weighty = 1;
c.insets = new Insets(10, 20, 10, 20);
c.fill = GridBagConstraints.HORIZONTAL;
page.add(subPanel, c);
}
JScrollPane scrollPane = new JScrollPane(page);
JFrame frame = new JFrame();
frame.setSize(300,500);
frame.add(scrollPane);
frame.setVisible(true);
}
}
I want to have label+textfield directly under the previous ones without filling the vertical space between (like when you resize my example vertically till you can see the vertical scrollbar). How can I achieve that? With my code the whole panel is filled vertically, but I don't want this.

Remove next line c.weighty = 1;.
Read more in docs.
Edit: use dummy JLabel for grabbing free space, after loop:
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 5;
c.fill = GridBagConstraints.BOTH;
c.weightx=1;
c.weighty=1;
c.gridwidth = 2;
page.add(new JLabel(" "),c);

I made a few changes to your code.
Always start a Swing application with a call to the SwingUtilities invokeLater method. This puts the Swing components on the Event Dispatch thread.
Since you're using the GridBagLayout, you can lay out your labels and text fields directly on the page JPanel.
I created a GridBagConstraints for each label and text field. That way, we're not relying on defaults. We specify the correct anchor and fill values for each component.
I added a couple of missing JFrame methods. You either have to specify a default close operation, or you have to close the application yourself. Without this specification, your application will continue to run after you close the main JFrame.
Edited to add:
To get the effect you want, put your page JPanel inside another JPanel. The outside JPanel has the FlowLayout.
Here's the modified code.
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class Spielklasse implements Runnable {
private static final Insets baseInsets =
new Insets(10, 20, 10, 20);
#Override
public void run() {
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new FlowLayout());
JPanel page = new JPanel();
page.setLayout(new GridBagLayout());
int gridy = 0;
for (int i = 0; i < 5; i++) {
JLabel label = new JLabel();
label.setText("Label " + i + ":");
addComponent(page, label, 0, gridy,
1, 1, baseInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
JTextField textField = new JTextField(20);
addComponent(page, textField, 1, gridy++,
1, 1, baseInsets, GridBagConstraints.LINE_START,
GridBagConstraints.HORIZONTAL);
}
mainPanel.add(page);
JScrollPane scrollPane = new JScrollPane(mainPanel);
JFrame frame = new JFrame("Spielklasse");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight,
Insets insets, int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 1.0D, 1.0D, anchor,
fill, insets, 0, 0);
container.add(component, gbc);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Spielklasse());
}
}

Related

How do I center label and button?

I want my Game to look like this:
but it wont and I don't know why.. everything just doesn't go in the places I want it to be.
Could someone help me? What am I doing wrong?
It looks like this:
The color-changing isn't the problem.. its just where all the stuff is located.
package view;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.weightx = 1;
gcon.weighty = 1;
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
}
As I understand you want the label and the button to be centered in the frame.
For this purpose do not set weightx and weighty since they will tell to layout manager to expand to the available space.
So remove
gcon.weightx = 1;
gcon.weighty = 1;
then, replace the following code
//label
gcon.gridx = 2;
gcon.gridy = 0;
//gcon.gridwidth = 4;
//gcon.gridheight = 1;
gb.setConstraints(label,gcon);
panel.add(label);
//button
gcon.gridx = 2;
gcon.gridy = 1;
//gcon.gridwidth = 2;
//gcon.gridheight = 1;
gb.setConstraints(button,gcon);
panel.add(button);
with this
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
Since no row and column has weight greater than 0 the layout manager will automatically place the label-button block in the middle.
Complete code
package test;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class WelcomeScreen extends JFrame{
JButton button;
JLabel label;
ActionListener action;
GridBagLayout gb = new GridBagLayout();
public <button> WelcomeScreen(ActionListener action){
JPanel panel = new JPanel();
this.setSize(800,600);
GridBagConstraints gcon = new GridBagConstraints();
gcon.fill = GridBagConstraints.HORIZONTAL;
gcon.insets = new Insets(5,5,5,5);
button = new JButton("Start");
button.setPreferredSize(new Dimension(200, 50));
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.CENTER);
label = new JLabel("Game");
label.setPreferredSize(new Dimension(200, 50));
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
this.action = action;
panel.setBorder(BorderFactory.createEmptyBorder(20, 10, 20, 10));
panel.setLayout(gb);
//label
gcon.gridx = 0;
gcon.gridy = 0;
panel.add(label, gcon);
//button
gcon.gridx = 0;
gcon.gridy = 1;
panel.add(button, gcon);
this.add(panel,BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Start");
this.setVisible(true);
button.addActionListener(action);
}
public static void main(String[] args) {
new WelcomeScreen(null).setVisible(true);
}
}
If you're willing to use Libraries I can recommend MigLayout.
Solution:
With MigLayout the code looks a bit more readable and it's generally easier:
JPanel contentPane = new JPanel(new MigLayout("", "[grow, center]", "[grow, center]"));
JPanel panel = new JPanel(new MigLayout("wrap 1", "[grow, fill]", "[]20px[]"));
JLabel label = new JLabel("Game");
label.setFont(new Font("Arial", Font.PLAIN, 60 ));
panel.add(label);
JButton button = new JButton("Start");
button.setFont(new Font("Arial", Font.PLAIN, 20 ));
button.setBorder(BorderFactory.createEmptyBorder(2, 10, 2, 2));
button.setHorizontalAlignment(SwingConstants.LEFT);
panel.add(button);
contentPane.add(panel);
setContentPane(contentPane);
Explanation:
The 'panel' is still the JPanel holding the components. The content is controlled by the layouts contraints:
The first argument of its MigLayout are the layout contrains and in that case it just auto wraps to the next line after each added component.
The second argument are the column contraints. Here it makes sure that the 'cells' (the layout manager works like a table) expand with 'grow' and the component inside that cell fill the whole cell with 'fill'.
The third argument are the row constraints. Here they just defines the gap between the rows. The '[]' in the column & row contrains stand for a column / row respectively. Anything inside that bracket defines how the cell and its content behaves, anything outside the brackets is used for defining gaps.
The 'contentPane' just makes sure that the 'panel' is centered inside using the same methods described above. It can then be added to a bigger component (like a frame) and expand, still keeping the content centered.
You should find all the info abould the Layouts capabilities at http://www.miglayout.com/whitepaper.html

GridBagLayout with glue : no fixed row height

I would like to create a panel, to which I can dynamically add sub-panels with fixed height. I tried using a glue component, but it does not work. I would like to achieve that the sub-panels are visible at the top of the gridbaglayout. Side problem is that when I keep adding sub-panels, they start to overlap because the JScrollPane isn't adjusting. However, when I resize the frame, both problems are solved.
At this moment I don't see where I went wrong. Why does the glue component not take up the vertical space to push the side panels to the top?
This is my SSCCE code:
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import jrdb.data.ProcessingCommand;
public class ProcessingPipelineBuilderSSCCE extends JFrame {
/**
*
*/
private static final long serialVersionUID = 2413084448601918744L;
private JPanel interiorPanel = null;
private GridBagConstraints gbc = null;
private Component glue = null;
public ProcessingPipelineBuilderSSCCE() {
super("SSCCE");
this.getContentPane().setLayout(new BorderLayout());
gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 5, 0, 5);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.PAGE_START;
JPanel pipelineBuilder = new JPanel();
pipelineBuilder.setLayout(new GridLayout(0, 1, 0, 0));
interiorPanel = new JPanel(new GridBagLayout());
interiorPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JScrollPane scrollPane = new JScrollPane(interiorPanel);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500,300));
pipelineBuilder.add(scrollPane);
JButton btnNew = new JButton("Add new panel");
btnNew.setPreferredSize(new Dimension(500, 30));
btnNew.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (glue!=null) {
interiorPanel.remove(glue);
} else {
glue = Box.createGlue();
}
gbc.gridy = gbc.gridy + 1;
interiorPanel.add(new PipelineStep(gbc.gridy),gbc);
interiorPanel.add(glue,gbc);
interiorPanel.validate();
interiorPanel.repaint();
}
});
this.getContentPane().add(btnNew, BorderLayout.PAGE_START);
this.getContentPane().add(pipelineBuilder,BorderLayout.CENTER);
}
public class PipelineStep extends JPanel {
int number;
public PipelineStep (int n) {
super();
JOptionPane.showMessageDialog(interiorPanel, "adding new panel");
this.number = n;
this.setLayout(new FlowLayout());
JLabel lbl = new JLabel(new Integer(this.number).toString());
lbl.setPreferredSize(new Dimension(45,45));
lbl.setFont(lbl.getFont().deriveFont(26));
this.add(lbl);
this.setPreferredSize(new Dimension(450, 50));
this.setBorder(BorderFactory.createLineBorder(Color.green));
}
}
public static void main (String args[]) {
ProcessingPipelineBuilderSSCCE frame = new ProcessingPipelineBuilderSSCCE();
frame.pack();
frame.setVisible(true);
}
}
Why does the glue component not take up the vertical space to push the side panels to the top?
The "glue" component only has meaning when used with the BoxLayout. It has no effect with the GridBagLayout.
So my suggestion is to forget about the GridBagLayout and use the BoxLayout.
The easiest way to do this is to convert "interiorPanel" to use a vertical Box and just add your PipelineStep instances to this panel.
Try this. However, you will notice that the panels will still increase in size until the scroll pane is full, at which time you will see scrollbars appear. This is because the BoxLayout will resize components up to the maximum size of the component. So to prevent this resizing you could override the getMaximumSize() method of your PipelineStep class:
#Override
public Dimension getMaximumSize()
{
return getPreferredSize();
}
Or, another option is to use a "wrapper" panel for your "interiorPanel". Something like:
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(interiorPanel, BorderLayout.PAGE_START);
//JScrollPane scrollPane = new JScrollPane(interiorPanel);
JScrollPane scrollPane = new JScrollPane(wrapper);
BorderLayout.PAGE_START respects the preferred height of the component added to it so the "interiorPanel" will always be displayed at it preferred height and scrollbars will appear when the viewport of the scroll pane is full.
I modified you code using the "wrapper" approach.
import javax.swing.*;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
//import jrdb.data.ProcessingCommand;
public class SSCCE1 extends JFrame {
/**
*
*/
private static final long serialVersionUID = 2413084448601918744L;
// private JPanel interiorPanel = null;
private Box interiorPanel = null;
private GridBagConstraints gbc = null;
private Component glue = null;
public SSCCE1() {
super("SSCCE");
this.getContentPane().setLayout(new BorderLayout());
gbc = new GridBagConstraints();
//gbc.insets = new Insets(5, 5, 0, 5);
//gbc.fill = GridBagConstraints.HORIZONTAL;
//gbc.gridx = 0;
//gbc.gridy = 0;
//gbc.weightx = 1.0;
//gbc.weighty = 1.0;
//gbc.anchor = GridBagConstraints.PAGE_START;
JPanel pipelineBuilder = new JPanel();
pipelineBuilder.setLayout(new GridLayout(0, 1, 0, 0));
// interiorPanel = new JPanel(new GridBagLayout());
interiorPanel = Box.createVerticalBox();
interiorPanel.setBorder(BorderFactory.createLineBorder(Color.red));
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add(interiorPanel, BorderLayout.PAGE_START);
// JScrollPane scrollPane = new JScrollPane(interiorPanel);
JScrollPane scrollPane = new JScrollPane(wrapper);
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(500,300));
pipelineBuilder.add(scrollPane);
JButton btnNew = new JButton("Add new panel");
btnNew.setPreferredSize(new Dimension(500, 30));
btnNew.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// if (glue!=null) {
// interiorPanel.remove(glue);
// } else {
// glue = Box.createGlue();
// }
gbc.gridy = gbc.gridy + 1;
// interiorPanel.add(new PipelineStep(gbc.gridy),gbc);
interiorPanel.add(new PipelineStep(gbc.gridy),gbc);
// interiorPanel.add(glue,gbc);
// interiorPanel.validate();
interiorPanel.revalidate();
interiorPanel.repaint();
}
});
this.getContentPane().add(btnNew, BorderLayout.PAGE_START);
this.getContentPane().add(pipelineBuilder,BorderLayout.CENTER);
}
public class PipelineStep extends JPanel {
int number;
public PipelineStep (int n) {
super();
JOptionPane.showMessageDialog(interiorPanel, "adding new panel");
this.number = n;
this.setLayout(new FlowLayout());
JLabel lbl = new JLabel(new Integer(this.number).toString());
lbl.setPreferredSize(new Dimension(45,45));
lbl.setFont(lbl.getFont().deriveFont(26));
this.add(lbl);
this.setPreferredSize(new Dimension(450, 50));
this.setBorder(BorderFactory.createLineBorder(Color.green));
}
}
public static void main (String args[]) {
SSCCE1 frame = new SSCCE1();
frame.pack();
frame.setVisible(true);
}
}

How to set correctly sizes of a jpanels?

I have a two jpanels: jpanel1 and jpanel2 which must have correct minimal size according to their content. jpanel0 is the container for these two panels, it must be on the left side of a frame. And here is jpanel3 that should take the rest of the available space on the right side.
How to set the size of a jpanel to all available space?
My desired output:
My current output:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class Panels {
public static void main(String[] args) {
JFrame myFrame = new JFrame();
myFrame.setLayout(new BorderLayout());
JTabbedPane jtp = new JTabbedPane();
JPanel jPaneTab1 = new JPanel();
jPaneTab1.setLayout(new FlowLayout(FlowLayout.LEFT));
JPanel jpanel0 = new JPanel();
jpanel0.setLayout(new BoxLayout(jpanel0, BoxLayout.Y_AXIS));
jpanel0.setBorder(BorderFactory.createTitledBorder("jpanel0"));
jpanel0.setBackground(Color.RED);
JPanel jpanel1 = new JPanel();
jpanel1.setLayout(new GridBagLayout());
jpanel1.setBorder(BorderFactory.createTitledBorder("jpanel1"));
GridBagConstraints gc = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel1 = new JLabel("jlabel1");
gc.gridx = 0;
gc.gridy = 0;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel1, gc);
JLabel jlabel2 = new JLabel("jlabel2");
gc.gridx = 0;
gc.gridy = 1;
gc.anchor = GridBagConstraints.NORTHWEST;
gc.insets = new Insets(0, 0, 0, 2);
jpanel1.add(jlabel2, gc);
JPanel jpanel2 = new JPanel();
jpanel2.setLayout(new GridBagLayout());
jpanel2.setBorder(BorderFactory.createTitledBorder("jpanel2"));
GridBagConstraints gc2 = new GridBagConstraints();
jpanel1.setBackground(Color.BLUE);
JLabel jlabel3 = new JLabel("jlabel3");
gc2.gridx = 0;
gc2.gridy = 0;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel3, gc2);
JLabel jlabel4 = new JLabel("jlabel4");
gc2.gridx = 0;
gc2.gridy = 1;
gc2.anchor = GridBagConstraints.NORTHWEST;
gc2.insets = new Insets(0, 0, 0, 2);
jpanel2.add(jlabel4, gc2);
JPanel jpanel3 = new JPanel();
jpanel3.setBackground(Color.YELLOW);
JLabel jlabel5 = new JLabel("jpanel3");
jpanel3.add(jlabel5);
jpanel0.add(jpanel1);
jpanel0.add(jpanel2);
jPaneTab1.add(jpanel0, BorderLayout.WEST);
jPaneTab1.add(jpanel3, BorderLayout.CENTER);
JPanel jPaneTab2 = new JPanel();
jtp.addTab("tab1", jPaneTab1);
jtp.addTab("tab2", jPaneTab2);
myFrame.add(jtp);
myFrame.setSize(800, 600);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
}
Addition:
When I use BorderLayout for main(tab panel) I'm getting another problem:
Layouts work easier when you break down the layout into logical panels and then nest panels with different layout managers.
For example, use a panel with a BorderLayout as the content for the tabbed pane.
Then you create a "ride side panel" and add it to this panel and a "center panel"
JPanel main = new JPanel( new BorderLayout() );
JPanel rightSide = new JPanel( ... );
JPanel center = new JPanel(...);
main.add(rightSide, BorderLayout.LINE_START);
main.add(center, BorderLayout.CENTER);
Then you set the layouts for the "rightSide" and "center" panels and add components to each of those panels.
You should not be using GridBagLayout, BorderLayout, or BoxLayout managers. These are outdated managers from the 90s.
For instance, when you do this:
gc.insets = new Insets(0, 0, 0, 2);
you are hardcoding pixel-width spaces between components, which
will not work across the wide variety of today's screens.
Insted, one should choose either GroupLayout or MigLayout.
Here is a working example with the MigLayout manager. Notice how easy
is to create the layout with this manager. (Four lines of code.) Also, we use logical pixels (lp) instead of physical pixels.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import net.miginfocom.swing.MigLayout;
public class PanelsEx extends JFrame {
public PanelsEx() {
initUI();
}
private void initUI() {
JTabbedPane tabpane = new JTabbedPane();
JPanel mainPanel = new JPanel();
JPanel pnl1 = createPanel("Panel 1");
JPanel pnl2 = createPanel("Panel 2");
JPanel pnl3 = createPanel("Panel 3");
mainPanel.setLayout(new MigLayout("ins 10lp"));
mainPanel.add(pnl1, "w 150lp, h 100lp, split 2, flowy, ay top");
mainPanel.add(pnl2, "w 150lp, h 100lp");
mainPanel.add(pnl3, "push, grow");
tabpane.add("First", mainPanel);
add(tabpane);
pack();
setTitle("Panels");
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private JPanel createPanel(String text) {
JLabel lbl = new JLabel(text);
JPanel pnl = new JPanel();
pnl.add(lbl);
pnl.setBorder(BorderFactory.createEtchedBorder());
return pnl;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
PanelsEx ex = new PanelsEx();
ex.setVisible(true);
});
}
}
And here is a screenshot:

Gridbag Layout, Insets or anchor won't take effect

Okay, so I need your help guys. I don't know what I missed but the insets and anchor is not taking effect even though I've set the layout to GridBag.
I need to put the logout button just above the tabbedpane and position the logout button on the upper right hand corner. In other words, tabbed pane on position gridx = 0, gridy = 1; and logout Button on position gridx = 0, gridy = 0;
Also, the myaccount button, leftpanel and rightpanel which are inside the home panel, won't get the insets i applied.
What am I missing. Please help because I'm new to this layout.
TopPanel.java
package MainComponents;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.border.Border;
import MainTab_TabbedPane.TopTabbedPane;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
public class TopPanel extends JPanel {
//DECLARATION
JButton logOutButton = new JButton("Logout");
TopTabbedPane topTabbedPane = new TopTabbedPane();
private final Border myLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
//CONSTRUCTOR
public TopPanel(){
setPanelInitialProperties();
addComponents();
}
//METHODS
private void setPanelInitialProperties(){
setLayout(new GridBagLayout());
setBorder(myLineBorder); //sets a Line Border for this panel
}
private void addComponents(){
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
this.add(topTabbedPane); //adds TabbedPane holding Home, Administration... to this Top Panel
gbc.gridx = 0;
gbc.gridy = 0;
this.add(logOutButton);
}
}
HomeTopPanel.java
package HomeTab;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
public class HomeTopPanel extends JPanel {
private final JButton MyAccountButton = new JButton("My Account");
private final JPanel leftPanel = new JPanel(new GridBagLayout());
private final JPanel rightPanel = new JPanel(new GridBagLayout());
private final Border leftPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
private final Border rightPanelLineBorder = BorderFactory.createLineBorder(Color.BLACK, 2);
//CONSTRUCTOR
public HomeTopPanel(){
constructMyAccountButton();
constructPanels();
setLeftRightPanelBorders();
this.setLayout(new GridBagLayout());
}
private void constructMyAccountButton(){
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
MyAccountButton_gbc.gridx = 0; MyAccountButton_gbc.gridy = 0;
MyAccountButton_gbc.anchor = GridBagConstraints.NORTHWEST;
this.add(MyAccountButton);
}
private void constructPanels(){
GridBagConstraints leftPanelgbc = new GridBagConstraints();
GridBagConstraints rightPanelgbc = new GridBagConstraints();
leftPanelgbc.insets = new Insets(3,3,3,3);
leftPanelgbc.gridx = 1; leftPanelgbc.gridy = 0;
leftPanel.setPreferredSize(new Dimension(300, 500));
this.add(leftPanel);
rightPanelgbc.insets = new Insets(3,3,3,3);
rightPanelgbc.gridx = 2; leftPanelgbc.gridy = 0;
rightPanel.setPreferredSize(new Dimension(300, 500));
this.add(rightPanel);
}
private void setLeftRightPanelBorders(){
leftPanel.setBorder(leftPanelLineBorder);
rightPanel.setBorder(rightPanelLineBorder);
this.setBorder(leftPanelLineBorder);
}
}
Thanks in advanced. I'm sure there's something I missed but I don't know.
INSETS won't apply. =( ??
UPDATE:
I added the insets with the following code:
private void constructPanels(){
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.gridx = 1; gbc2.gridy = 0;
gbc2.insets = new Insets(5, 5, 5, 5);
leftPanel.setPreferredSize(new Dimension(250, 300));
this.add(leftPanel,gbc2);
gbc2.gridx = 2; gbc2.gridy = 0;
gbc2.insets = new Insets(5, 5, 5, 5);
rightPanel.setPreferredSize(new Dimension(300, 500));
this.add(rightPanel,gbc2);
}
but still not getting any inset of 5.
Apply the constraints when adding components
add(topTabbedPane, gbc);
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
Variable names should NOT start with an upper case character. Most of your other names are correct. Then is no reason to be sloppy. Follow the Java conventions.
constructMyAccountButton();
constructPanels();
setLeftRightPanelBorders();
this.setLayout(new GridBagLayout());
The layout must be set BEFORE you add components to the panel.
GridBagConstraints MyAccountButton_gbc = new GridBagConstraints();
MyAccountButton_gbc.gridx = 0; MyAccountButton_gbc.gridy = 0;
MyAccountButton_gbc.anchor = GridBagConstraints.NORTHWEST;
//this.add(MyAccountButton); // where is the constraint?
this.add(MyAccountButton, myAccountButton_gbc);
You actually have to use the constraint.

Alignment issues with BoxLayout

I am making an application for which I am using a BoxLayout. As you can see in the following picture, when the title string is short, it's perfect. But as the string gets longer, the JLabel gets more and more misaligned.
Here's some code that is related to the problem:
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BoxLayout(centerPanel, BoxLayout.PAGE_AXIS));
frame.add(centerPanel, BorderLayout.CENTER);
//...
JLabel l = new JLabel(/*...*/);
l.setHorizontalAlignment(SwingConstants.CENTER); //I tried removing and adding
//this but nothing changed
centerPanel.add(l);
Is there something obvious I am missing? Google isn't being helpful with this problem.
In case it's important, the country-label-progress-bar things are just JPanels with FlowLayouts.
SSCCE:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SSCCE {
public static void main(String[] args) {
final JFrame f = new JFrame("SSCCE");
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
final JLabel[] titles = new JLabel[5];
JPanel[] smallPanels = new JPanel[titles.length];
for (int i = 0; i < smallPanels.length; i ++) {
titles[i] = new JLabel(Math.random() < 0.5 ? "foo" : "bar");
p.add(titles[i]);
smallPanels[i] = new JPanel();
smallPanels[i].add(new JLabel("foobar"));
smallPanels[i].add(new JProgressBar());
p.add(smallPanels[i]);
}
f.add(p, BorderLayout.CENTER);
final JTextField tf = new JTextField("foobar");
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
titles[2].setText(tf.getText());
f.repaint();
}
});
f.add(tf, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(600, 600);
f.setVisible(true);
}
}
To operate the SSCCE, type something in the text field and press enter.
Here is an updated version of your SSCCE with a GridBagLayout. Not sure of how you want components to resize when labels or frame size changes but it should not be too hard to manage this.
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextField;
public class SSCCE {
public static void main(String[] args) {
final JFrame f = new JFrame("SSCCE");
JPanel p = new JPanel();
p.setLayout(new GridBagLayout());
Insets insets = new Insets(3, 3, 3, 3);
GridBagConstraints gbc1 = new GridBagConstraints();
gbc1.gridwidth = GridBagConstraints.REMAINDER;
gbc1.anchor = GridBagConstraints.CENTER;
gbc1.insets = insets;
GridBagConstraints gbc2 = new GridBagConstraints();
gbc2.anchor = GridBagConstraints.EAST;
gbc2.insets = insets;
GridBagConstraints gbc3 = new GridBagConstraints();
gbc3.weightx = 1.0;
gbc3.fill = GridBagConstraints.HORIZONTAL;
gbc3.gridwidth = GridBagConstraints.REMAINDER;
gbc3.insets = insets;
final JLabel[] titles = new JLabel[5];
Random random = new Random();
for (int i = 0; i < titles.length; i++) {
titles[i] = new JLabel(Math.random() < 0.5 ? "foo" : "bar");
p.add(titles[i], gbc1);
p.add(new JLabel("foobar"), gbc2);
JProgressBar progress = new JProgressBar();
progress.setStringPainted(true);
progress.setString(String.valueOf(random.nextInt(100)));
p.add(progress, gbc3);
}
f.add(p, BorderLayout.CENTER);
final JTextField tf = new JTextField("foobar");
tf.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
titles[2].setText(tf.getText());
f.repaint();
}
});
f.add(tf, BorderLayout.NORTH);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
}
BoxLayout accepting Min, Max and PreferredSize, childs could be resizable from Min to MaxSize
FlowLayout accepting only PreferredSize, rest (Min, MaxSize) is ignored by this LayoutManager, childs aren't resizable
these XxxSize are calculated from PreferredSize came from childs placed into container (JPanel in this case)
(your question) for better help sooner post an SSCCE, short, runnable, compilable, just about your issue

Categories

Resources