Java: MigLayout Center Center not working | alternative for absolute positioning - java

The element won't center vertically, and I don't know why. I've tried "center center", but it's not working.
MigLayout
private JPanel panel = new JPanel(new MigLayout("center center, filly"));
Components
panel.add(header, "span");
panel.add(input, "split 4");
panel.add(unit1);
panel.add(to);
panel.add(unit2, "wrap");
panel.add(convert, "span");
panel.add(output, "span");
I want to center the components, but not using absolute positioning (because I know how to center using this method)

TL;DR
Shame on you but
center center is not center, center
center, center, filly - filly mitigates the vertical center
To align individual components, you need align center - For example, panel.add(new JLabel("Header"), "span, align center");
Assuming you are asking how to horizontally align the components, you need to specify that per component. However, first it is best to look at what the following line of code actually does.
private JPanel panel = new JPanel(new MigLayout("center center, filly"));
Or more specifically, what the following extract means.
new MigLayout("center center, filly")
center center - This horizontally aligns the packed components on the JPanel.
Assuming you were trying to get the components centered vertically as well as horizontally, you would actually need center, center. Notice the , between the two center keywords.
filly - Well to quote the white paper, "Claims all available space in the container for the columns and/or rows".
This pretty much mitigates the effect of "center, center" and all you really need is center, filly.
Now to horizontally align components across multiple columns, you need to add the keywords align center to each component you want to do this on. For example
panel.add(new JLabel("Header"), "span, align center");
An example of this with your components would be
String[] dummyList = new String[] {
"Val 1",
"Val 2"
};
JPanel migPanel = new JPanel(new MigLayout("center, filly")); //Maybe you wanted center, center. I'm not sure
migPanel.add(new JLabel("Header"), "span, align center");
migPanel.add(new JTextField("Input"), "split 4");
migPanel.add(new JComboBox<String>(dummyList));
migPanel.add(new JLabel("To"), "span");
migPanel.add(new JComboBox<String>(dummyList), "wrap");
migPanel.add(new JButton("Convert"), "span, align center");
migPanel.add(new JTextField("Output"), "span, align center");
As MadProgrammer mentioned there are other layouts that can be used to achieve a very similar look to what you had; GridBagLayout being the easiest.
Using a mixture of GridBagConstraints you can achieve a very similar layout.
For example,
String[] dummyList = new String[] {
"Val 1",
"Val 2"
};
JPanel gridBagPanel = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weighty = 1; //Delete this line if you are after an equivalent of `center, center` from the MigLayout
gc.gridwidth = 4;
gridBagPanel.add(new JLabel("Header"), gc);
gc.gridy = 1;
gc.gridwidth = 1;
gridBagPanel.add(new JTextField("Input"), gc);
gc.gridx = 1;
gridBagPanel.add(new JComboBox<String>(dummyList), gc);
gc.gridx = 2;
gridBagPanel.add(new JLabel("To"), gc);
gc.gridx = 3;
gridBagPanel.add(new JComboBox<String>(dummyList), gc);
gc.gridy = 2;
gc.gridx = 0;
gc.gridwidth = 4;
gridBagPanel.add(new JButton("Convert"), gc);
gc.gridy = 3;
gridBagPanel.add(new JTextField("Output"), gc);
Runnable Example - LayoutExample.java
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
#SuppressWarnings("serial")
public class LayoutExample extends JFrame {
private JTabbedPane tabs;
private JPanel migPanel;
private JPanel gridBagPanel;
private JPanel migPanelCC;
private JPanel gridBagPanelCC;
private String[] dummyList = new String[] {
"Val 1",
"Val 2"
};
private LayoutExample() {
super("Layout Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setUpTabs();
add(tabs);
setSize(800, 500);
setVisible(true);
}
private void setUpTabs() {
tabs = new JTabbedPane();
setUpMig();
tabs.add(migPanel, "Mig Panel");
setUpMigCC();
tabs.add(migPanelCC, "Mig Panel Center Center");
setUpGridBag();
tabs.add(gridBagPanel, "Grid Bag Panel");
setUpGridBagCC();
tabs.add(gridBagPanelCC, "Grid Bag Panel Center Center");
}
private void setUpMig() {
migPanel = new JPanel(new MigLayout("center, filly"));
addToMigPanel(migPanel);
}
private void setUpMigCC() {
migPanelCC = new JPanel(new MigLayout("center, center"));
addToMigPanel(migPanelCC);
}
private void addToMigPanel(JPanel mPanel) {
mPanel.add(new JLabel("Header"), "span, align center");
mPanel.add(new JTextField("Input"), "split 4");
mPanel.add(new JComboBox<String>(dummyList));
mPanel.add(new JLabel("To"), "span");
mPanel.add(new JComboBox<String>(dummyList), "wrap");
mPanel.add(new JButton("Convert"), "span, align center");
mPanel.add(new JTextField("Output"), "span, align center");
}
private void setUpGridBag() {
gridBagPanel = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weighty = 1;
addToGridBagPanel(gridBagPanel, gc);
}
private void setUpGridBagCC() {
gridBagPanelCC = new JPanel(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
addToGridBagPanel(gridBagPanelCC, gc);
}
private void addToGridBagPanel(JPanel gblPanel, GridBagConstraints gc) {
gc.gridwidth = 4;
gblPanel.add(new JLabel("Header"), gc);
gc.gridy = 1;
gc.gridwidth = 1;
gblPanel.add(new JTextField("Input"), gc);
gc.gridx = 1;
gblPanel.add(new JComboBox<String>(dummyList), gc);
gc.gridx = 2;
gblPanel.add(new JLabel("To"), gc);
gc.gridx = 3;
gblPanel.add(new JComboBox<String>(dummyList), gc);
gc.gridy = 2;
gc.gridx = 0;
gc.gridwidth = 4;
gblPanel.add(new JButton("Convert"), gc);
gc.gridy = 3;
gblPanel.add(new JTextField("Output"), gc);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new LayoutExample());
}
}
Finally, it is a bad idea to use absolute positioning. This is because when the container changes size, the components within the container will not automatically adjust. This will not work well for most things as you could lose important UI components pretty fast or you could have loads of extra white space.

Related

Can not figure out a simple 4 box JPanel layout

I have been trying for hours to get JPanel in Java to contain these 4 other panels in this configuration (see picture)
The blue box should never change size.
The white box should never change height, can get wider though.
The dark grey box should never change widths, can get taller though.
The light grey box can get taller or wider.
Seems pretty simple to me, I did it in C# the other day and it was a breeze. Set the position, the width, height, and whether a certain side was anchored or not, boom done, I was starting to like java more than C until I ran into this.
I've tried countless combinations of GridBagLayout, multiple nested BoxLayout instances. They all seem to do very strange things, like make each panel a tiny 4 x 4 square, or there is crazy padding around them, or the ones that need to re-size with the window, don't.
Is there some kind of magic combination that can achieve this? Does the null layout do anchoring or percent dimensions.
The closest I've gotten is the bottom image with GridBagLayout, which looks good when it loads, but does that when you re-size the window.
Here is the code that got the above images
class MainPanel extends JPanel {
public MainPanel(){
this.setBackground(new Color(216,216,216));
this.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
JPanel topTitle = new JPanel();
topTitle.setPreferredSize(new Dimension(140, 40));
topTitle.setMinimumSize(new Dimension(140, 40));
topTitle.setBackground(new Color(174, 216, 249));
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
this.add(topTitle,c);
JPanel mainHeader = new JPanel();
mainHeader.setPreferredSize(new Dimension(1060, 40));
mainHeader.setMinimumSize(new Dimension(1060, 40));
mainHeader.setBackground(Color.WHITE);
c.gridx = 1;
c.gridy = 0;
this.add(mainHeader,c);
JPanel sideNav = new JPanel();
sideNav.setPreferredSize(new Dimension(140, 760));
sideNav.setMinimumSize(new Dimension(140, 760));
sideNav.setBackground(new Color(110,110,110));
c.gridx = 0;
c.gridy = 1;
this.add(sideNav,c);
JPanel dataPanel = new JPanel();
dataPanel.setPreferredSize(new Dimension(1060, 760));
dataPanel.setMinimumSize(new Dimension(1060, 760));
dataPanel.setBackground(new Color(216,216,216));
c.gridx = 1;
c.gridy = 1;
this.add(dataPanel,c);
}
}
GUI at minimum size
GUI stretched wider & taller
It's all about getting appropriate resize weights & fill values..
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
public class FourPanelLayout {
private JComponent ui = null;
FourPanelLayout() {
initUI();
}
public void initUI() {
if (ui!=null) return;
ui = new JPanel(new GridBagLayout());
// It appears you don't want space around the panels.
// If not, commment out or remove this line.
ui.setBorder(new EmptyBorder(4,4,4,4));
// create the panels, each with a transparent image to suggest a size
JPanel bluePanel = new JPanel();
bluePanel.setBackground(Color.CYAN);
bluePanel.add(new JLabel(new ImageIcon(getTransparentImage(40, 20))));
JPanel darkGrayPanel = new JPanel();
darkGrayPanel.setBackground(Color.DARK_GRAY);
darkGrayPanel.add(new JLabel(new ImageIcon(getTransparentImage(40, 20))));
JPanel whitePanel = new JPanel();
whitePanel.setBackground(Color.WHITE);
whitePanel.add(new JLabel(new ImageIcon(getTransparentImage(40, 20))));
JPanel grayPanel = new JPanel();
grayPanel.setBackground(Color.GRAY);
grayPanel.add(new JLabel(new ImageIcon(getTransparentImage(360, 80))));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 0.0f;
gbc.weighty = 0.0f;
gbc.gridx = 0;
gbc.gridy = 0;
ui.add(bluePanel, gbc);
gbc.weightx = .5f;
gbc.gridx = 1;
ui.add(whitePanel, gbc);
gbc.weighty = .5f;
gbc.gridy = 1;
ui.add(grayPanel, gbc);
gbc.weightx = 0f;
gbc.gridx = 0;
//gbc.gridy
ui.add(darkGrayPanel, gbc);
}
/* We use transparent images to give panels a natural size. */
private Image getTransparentImage(int w, int h) {
return new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
}
public JComponent getUI() {
return ui;
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception useDefault) {
}
FourPanelLayout o = new FourPanelLayout();
JFrame f = new JFrame(o.getClass().getSimpleName());
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setLocationByPlatform(true);
f.setContentPane(o.getUI());
f.pack();
f.setMinimumSize(f.getSize());
f.setVisible(true);
}
};
SwingUtilities.invokeLater(r);
}
}
To implement this, I recommended to use FormLayout.
FormLayout is a powerful, flexible and precise general purpose layout manager. It places components in a grid of columns and rows, allowing specified components to span multiple columns or rows. Not all columns/rows necessarily have the same width/height.
Note: It good to use Windowbuilder in Eclipse or GUI Form in Intellij to automatically place and set the components properties.

JTextField is stacking on top of JTextArea

I'm working on a small GUI project that builds a book manger to mange a book. In my layout, I want a textArea to display information about my book, a text JLabel underneath my textArea and a JTextArea for me to input information same column of JLabel and 1 row next to Label. However when I run my program, textArea and Label is completely cover over my textArea.
How can I fix this problem. Thanks!!
import java.awt.*;
import javax.swing.*;
public class Design extends JFrame {
JButton button1;
JTextArea outputArea;
JLabel stockLabel, bookPriceLabel;
JTextField stockTextField, priceTextField;
JPanel panel;
GridBagConstraints gc;
public Design(){
super("Book Info");
gc = new GridBagConstraints ();
panel = new JPanel();
outputArea = new JTextArea(20, 50);
stockLabel = new JLabel ("Books In Stock");
bookPriceLabel = new JLabel("Book Price");
stockTextField = new JTextField(10);
button1 = new JButton ("button1");
panel.setLayout(new GridBagLayout());
panel.setSize(600, 600);
gc.anchor = GridBagConstraints.NORTHWEST;
gc.weightx = 1;
gc.weighty = 1;
panel.add(outputArea, gc);
gc.gridx = 2;
gc.gridy = 2;
panel.add(stockLabel, gc);
gc.gridx = 3;
gc.gridy = 2;
panel.add(stockTextField, gc);
this.getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setVisible(true);
setLocationRelativeTo(null);
}
public static void main (String args[]){
Design frame = new Design();
}
}
You could apply a gridWidth constraint to the JTextArea which would allow it to span multiple columns.
Remember, GridBagLayout is still based around the concept of a grid (rows and columns), but which provides a lot of flexibility to customise how components fill and span through out that grid
Maybe something like...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Design extends JFrame {
JButton button1;
JTextArea outputArea;
JLabel stockLabel, bookPriceLabel;
JTextField stockTextField, priceTextField;
JPanel panel;
GridBagConstraints gc;
public Design() {
super("Book Info");
gc = new GridBagConstraints();
panel = new JPanel();
outputArea = new JTextArea(20, 50);
stockLabel = new JLabel("Books In Stock");
bookPriceLabel = new JLabel("Book Price");
stockTextField = new JTextField(10);
button1 = new JButton("button1");
panel.setLayout(new GridBagLayout());
gc.anchor = GridBagConstraints.NORTHWEST;
gc.gridx = 0;
gc.gridy = 0;
gc.weightx = 1;
gc.weighty = 1;
gc.gridwidth = GridBagConstraints.REMAINDER;
panel.add(new JScrollPane(outputArea), gc);
gc.weightx = 0;
gc.weighty = 0;
gc.anchor = GridBagConstraints.WEST;
gc.gridwidth = 1;
gc.gridx = 0;
gc.gridy = 2;
panel.add(stockLabel, gc);
gc.gridx++;
gc.gridy = 2;
panel.add(stockTextField, gc);
this.getContentPane().add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
setLocationRelativeTo(null);
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Design frame = new Design();
}
});
}
}
See How to Use GridBagLayout for more details
Some general feedback:
There's no point in calling setSize on a component which will be added to a container which using a layout manager, the action will simply be ignored and the layout manager will call setSize with what it wants to use
JTextArea really should be contained within a JScrollPane, you'll get some weird results if you don't (it will want to grow as the text occupies more space)
Prefer JFrame#pack over JFrame#setSize, this will take into account the frame borders, wrapping the frame around the contents
You really should avoid extending directly from top level containers like JFrame, apart from locking you into a single use case, you're really not adding any new functionality to the frame. Instead, start with something like a JPanel, build you core UI ontop of that and then, when you need to, add that to what ever container you want

GridBagLayout not getting expected result

Trying to understand how the GridBagLayout for Java works. Never used it before so its probably a stupid error that I've made.
My objective is to place a JLabel at the top center of the page. I've been using the java tutorials on Oracle but have had no luck. It seems the label remains in the center of the page. (center as in dead center of the x and y graph).
From what I understood, if I set the gridx and gridy constraint to 0, the compiler will look at the top, first row of the program and place the text their. I then used the PAGE START anchor to place the text in the center of the page. I'm not entirely sure what the weightx and weighty function does in my defence.
import javax.swing.*;
import java.awt.*;
class test
{
public static void main (String Args [])
{
//frame and jpanel stuff
JFrame processDetail = new JFrame("Enter information for processes");
JPanel panelDetail = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//label to add on top centre
JLabel label = new JLabel("LOOK AT ME");
//set size of frame and operation
processDetail.setSize(500,500);
processDetail.setDefaultCloseOperation(processDetail.EXIT_ON_CLOSE);
//add the label to panel
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.PAGE_START;
c.weightx = 0; //not sure what this does entirely
c.gridx = 0; //first column
c.gridy = 0; //first row
panelDetail.add(label, c);
processDetail.add(panelDetail);
processDetail.setVisible(true);
}
}
You're only adding one thing to the GBL using container, and so it will be centered. If you add a 2nd component below your JLabel, the JLabel will show up at the top. For example,
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class Test2 {
private static void createAndShowGui() {
JPanel mainPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.PAGE_START;
mainPanel.add(new JLabel("Look at me!", SwingConstants.CENTER), gbc);
gbc.gridy = 1;
gbc.gridheight = 10;
gbc.gridwidth = 10;
mainPanel.add(Box.createRigidArea(new Dimension(400, 400)), gbc);
JFrame frame = new JFrame("Test2");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Myself, I'd use BorderLayout if I wanted my JLabel to be at the top.

Java GridBagLayout

I've been tasked with designing a basic UI in Java using Swing but I'm stuck with laying it out. I want to create something similar to this but my attempts at using GridBagLayout have resulted in something very messy. Can anyone offer some tips on how I can lay out my GUI like this?
I have a JTabbedPane to which I add two tabs, and to each of those two tabs I add a JPanel containing my controls.
I would recommend that
the overall GUI use BorderLayout,
the JTable be in a JScrollPane and this should be placed BorderLayout.CENTER.
The top JPanel holding labels, fields, and buttons be placed BorderLayout.PAGE_START.
The top JPanel also can use BorderLayout and can hold the buttons in the BorderLayout.PAGE_END position.
The buttons would be held by a GridLayout(1, 0, x, 0) using JPanel where x is the gap between buttons
The labels and JTextFields be in a JPanel that uses GridBagLayout and that is placed in the top JPanel in the BorderLayout.CENTER position.
that you not follow these recommendations blindly but instead that you experiment with and play with different combinations of nested JPanels, each using its own layout.
that you also check out this link
Here's what I would recommend:
Use a JPanel pTextBox with GridLayout(3, 2) to hold all of your labels + textboxes
Use a JPanel pButtons with GridLayout(1, 3) or BoxLayout(horizontal) hold all of your buttons
Use a JPanel pAll with BoxLayout(vertical) to hold pTextBox, pButtons and the Table.
Use struts, glues, and min/max/prefererd sizes to adjust spacing / resizing behaviour.
Also check out: http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html to compare exactly what you are looking for.
There is a component, the JTable, that wants to occupy all the available space in the window. That means that a BorderLayout will be needed, with a JScrollPane that contains the JTable in the BorderLayout.CENTER of that BorderLayout. The other components will be inside another JPanel in the BorderLayout.PAGE_START
In this new JPanel, there is no component that needs to adjust its size vertically, so i don't see the necessity of a BorderLayout. I would compose it with a vertical BoxLayout. Insert in this panel two more, one GridBagLayout for the labels and text fields, and below one FlowLayout for the buttons, with center alignment and some horizontal gap. I prefer FlowLayout insetad of GridLayout for the buttons because if you resize the main panel, with a FlowLayout the buttons will keep the same distance between them.
Here's some code...I couldn't get the JTextFields to display correctly so you'll have to fix that.
Main:
import javax.swing.SwingUtilities;
public class Main {
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
Panel panel = new Panel();
}
});
}
}
Panel:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
public class Panel extends JPanel{
private JFrame frame;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JButton button1;
private JButton button2;
private JButton button3;
private JTable table;
public Panel() {
label1 = new JLabel("label1");
label2 = new JLabel("label2");
label3 = new JLabel("label3");
textField1 = new JTextField("textField1", 20);
textField2 = new JTextField("textField2", 20);
textField3 = new JTextField("textField3", 100);
button1 = new JButton("Hello");
button2 = new JButton("Goodbye");
button3 = new JButton("Love");
table = new JTable(20,20);
frame = new JFrame("My application");
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
this.setOpaque(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1;
gc.weighty =1;
gc.fill = GridBagConstraints.NONE;
gc.gridx = 0;
gc.gridy = 0;
// gc.anchor = GridBagConstraints.WEST;
add(label1, gc);
gc.gridx = 2;
gc.gridy = 0;
//gc.anchor = GridBagConstraints.EAST;
add(textField1, gc);
gc.gridx = 0;
gc.gridy = 1;
//gc.anchor = GridBagConstraints.WEST;
add(label2, gc);
gc.gridx = 2;
gc.gridy = 1;
//gc.anchor = GridBagConstraints.EAST;
add(textField2, gc);
gc.gridx = 0;
gc.gridy = 2;
//gc.anchor = GridBagConstraints.WEST;
add(label3, gc);
gc.gridx = 2;
gc.gridy = 2;
//gc.anchor = GridBagConstraints.EAST;
add(textField3, gc);
gc.gridx = 0;
gc.gridy = 3;
//gc.anchor = GridBagConstraints.WEST;
add(button1, gc);
gc.gridx = 1;
gc.gridy = 3;
gc.anchor = GridBagConstraints.CENTER;
add(button2, gc);
gc.gridx = 2;
gc.gridy = 3;
// gc.anchor = GridBagConstraints.EAST;
add(button3, gc);
gc.gridx = 1;
gc.gridy = 4;
gc.anchor = GridBagConstraints.CENTER;
add(table, gc);
frame.add(this);
}
}

Not able to add 3 JPanels to a main panel

I have 3 JPanels and I want to place them all in one JPanel. I used the GridBagLayout for the main panel. But only one panel is getting added. Why might this be?
gblayout=new GridBagLayout();
gbc=new GridBagConstraints();
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(gblayout);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbc.anchor=GridBagConstraints.NORTHWEST;
gbc.weightx=1;
gbc.weighty=1;
gbc.gridheight=GridBagConstraints.REMAINDER;
add(panel1, gbc);
add(panel2, gbc);
gbc.gridwidth=GridBagConstraints.REMAINDER;
add(panel3, gbc);
The customizer methods are ones which add items into these panels.
I am not sure but I think you need to add a GridBagConstraints to your GridBagLayout. Try look at this site to get the idea on how to work with GridBagLayout:
link
Or maybe just use another Layout for your JFrame, maybe BorderLayout or GridLayout to arrange your Panels correctly
You should change gbc.gridx and/or gbc.gridy to be different for each panel
you have to read How to Use GridBagLayout, examples for that here and GridBagConstraints, change your gbc.fill=GridBagConstraints.HORIZONTAL;, if you have problem(s) with JComponent's Size then add setPreferedSize(); for example
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GBLFillBoth extends JFrame {
private static final long serialVersionUID = 1L;
public GBLFillBoth() {
JPanel panel = new JPanel();
GridBagLayout gbag = new GridBagLayout();
panel.setLayout(gbag);
GridBagConstraints c = new GridBagConstraints();
JButton btn1 = new JButton("One");
c.fill = GridBagConstraints.BOTH;
//c.fill = GridBagConstraints.HORIZONTAL;
c.anchor=GridBagConstraints.NORTHWEST;
c.gridx = 0;
c.gridy = 0;
c.weightx = 0.5;
c.weighty = 0.5;
panel.add(btn1, c);
JButton btn2 = new JButton("Two");
c.gridx++;
panel.add(btn2, c);
//c.fill = GridBagConstraints.BOTH;
JButton btn3 = new JButton("Three");
c.gridx = 0;
c.gridy++;
c.gridwidth = 2;
panel.add(btn3, c);
add(panel);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String[] args) {
GBLFillBoth gBLFillBoth = new GBLFillBoth();
}
}
You might consider using a MigLayout instead, the code is much simpler:
panel1Customizer();
panel2customizer();
panel3Customizer();
setLayout(new MigLayout("fill, wrap 3"));
add(panel1, "grow");
add(panel2, "grow");
add(panel3, "grow");

Categories