Gridbag layout -> how to stop components from resizing along with the window? - java

I have a JFframe form in NetBeans 8 / Java 7.
It has a bunch of labels, textboxes, dropdowns, etc.
These are a column on the left size, all staked up on top of each other.
Here's a screenshot:
How can I prevent all those components from sticking to the right and resizing along with the window and at the same time have the preview frame at the far right resize along?
I'm new to Java, and the gridbaglayout was the only I found to align everything properly. I just want the left side to have its components well aligned and not moving around. And I just want the right side, the panel, to resize according to the window resize.
Thank you,

I just want the right side, the panel, to resize according to the window resize.
By default all the columns are divided in equal percentage in each row.
To force the second (right side) column to take the more space, assign it a higher percentage using GridBagConstraints#weightx
gc.weightx = 0.75; // 75%
Don't forget to fill the horizontal space completely using GridBagConstraints#fill
gc.fill = GridBagConstraints.HORIZONTAL;
If you want fixed width for first column then set the preferred size for the left side panel by overriding getPreferredSize() method and assign 100% width to the right side panel.
JPanel leftSidePanel = new JPanel() {
#Override
public Dimension getPreferredSize() {
return new Dimension(..., ...);
}
}
Have a look at my another post GridBagLayout: How to set fixed column width? that explain it better.
It;s worth reading Swing Tutorial on Solving Common Layout Problems

You need to set the fill constraint to NONE.
Tutorial: How to Use GridBagLayout:
When you add each Component to the panel, it would look something like this (from the tutorial):
JPanel pane = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//For each component to be added to this container:
//...Create the component...
//...Set instance variables in the GridBagConstraints instance...
pane.add(theComponent, c);
you need to ensure that you call:
c.fill = GridBagConstraints.NONE;
for every constraints object for each Component that you add to the panel that you don't want to stretch horizontally.
If you're resusing the same constraints object for each component, you can simply set it once for all if that's you're desired result.
EDIT:
As some others have pointed out, the OP may want the fields to stretch, but only up to a certain limit (which is still not clear at this point). In that case, you would use a combination of
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0;
as already pointed out. Example:
import java.awt.*;
import javax.swing.*;
public class GridBagDemo implements Runnable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new GridBagDemo());
}
public void run()
{
// 4 components that all have different widths
JButton btnBrowse = new JButton("Browse");
JTextField txfHeight = new JTextField(4);
JTextField txfWidth = new JTextField(10);
JButton btnMore = new JButton("More PDF Attributes");
// the preview pane?
JTextArea txaPreview = new JTextArea(8, 20);
JScrollPane scrPreview = new JScrollPane(txaPreview);
scrPreview.setVerticalScrollBarPolicy(
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
GridBagConstraints gbc = new GridBagConstraints();
// we'll use these constraints for all components
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(2,4,2,4);
JPanel panel = new JPanel(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
panel.add(new JLabel("Source PDF size..."), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 2;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(btnBrowse, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
panel.add(new JLabel("Height (in inches):"), gbc);
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(txfHeight, gbc);
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
panel.add(new JLabel("Width (in inches):"), gbc);
gbc.gridx = 1;
gbc.gridy = 3;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(txfWidth, gbc);
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.HORIZONTAL;
panel.add(btnMore, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1;
panel.add(Box.createVerticalGlue(), gbc);
gbc.gridx = 2;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0;
gbc.weighty = 0;
panel.add(new JLabel("Preview"), gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.gridwidth = 1;
gbc.gridheight = 8; // some number that's > the number of entry rows
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
panel.add(scrPreview, gbc);
JFrame frame = new JFrame("GrigBag Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(panel), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}

the gridbaglayout was the only I found to align everything properly.
The MigLayout manager can do that easily. It also provides much better portability.
Notice the usage of related gaps (r), dialog insets (dialog) and logical pixels (lp).
These units are translated to pixels accordingly. On the other hand, GridbagLayout
sets spaces directly in pixels which is inadequate, e.g. changing font or resolution
will affect the layout.
See to following code example:
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class MigLayoutPreview2 extends JFrame {
public MigLayoutPreview2() {
initUI();
setTitle("Design preview");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private void initUI() {
JPanel pnl = new JPanel(new MigLayout("ins dialog, wrap"));
pnl.add(new JLabel("Source PDF file..."), "pad 0 -5lp 0 0");
pnl.add(new JButton("Browse"), "growx");
pnl.add(new JLabel("Height (inches):"), "sgx, split 2");
pnl.add(new JTextField(10), "growx");
pnl.add(new JLabel("Width (inches):"), "sgx, split 2");
pnl.add(new JTextField(10), "growx");
pnl.add(new JButton("More PDF attributes"), "growx");
pnl.add(new JSeparator(), "pad 0 -5lp 0 0, gaptop r, growx");
pnl.add(new JLabel("Set bounding box..."), "pad 0 -5lp 0 0");
pnl.add(new JComboBox(), "growx");
pnl.add(new JSeparator(), "pad 0 -5lp 0 0, gaptop r, growx");
pnl.add(new JLabel("Sheet size..."), "pad 0 -5lp 0 0");
pnl.add(new JComboBox(), "growx");
pnl.add(new JLabel("Height (inches):"), "sgx, split 2");
pnl.add(new JTextField(10), "growx");
pnl.add(new JLabel("Width (inches):"), "sgx, split 2");
pnl.add(new JTextField(10), "growx");
pnl.add(new JSeparator(), "pad 0 -5lp 0 0, gaptop r, growx");
JPanel rpnl = new JPanel();
rpnl.setBorder(BorderFactory.createEtchedBorder());
pnl.add(rpnl, "cell 2 0, w 90, spany, pushx, grow");
add(pnl);
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
MigLayoutPreview2 ex = new MigLayoutPreview2();
ex.setVisible(true);
}
});
}
}
I have reproduced part of your screenshot and have also kept the indents.
Horizontal separators do not stretch completly, since I believe this is not
optimal design. The design is also improved by eliminating the huge spaces
between labels and text fields.

Related

Im having trouble trying to display graphics in my JFrame

I am trying to create game with a similar layout to Wordle where there is a 5 letter scrambled word displayed and below it there are 5 separate text fields for the user to input what order the letters of the scrambled word will go in. Basically they have to unscramble the word. Sorry for the bad explanation.
Iam trying to make rectangles/squares around each of the letters of the JLabels lb1, lb2, lb3, lb4, lb5 and around each of the JTextFields tf1, tf2, tf3, tf4, tf5. I cannot figure out how to display these rectangles at all but also how they will display on top of JPanels that are already in place.
Also just a bonus here, Is there anyway to organise these labels and text fields so that i can set there exact position? i would like to have 5 of the labels on top of 5 of the text fields.
import java.awt.*;
import javax.swing.*;
public class scramble extends JFrame {
Font mainFont = new Font("Impact", Font.BOLD, 60);
Font smallFont = new Font("Impact", Font.BOLD, 30);
JLabel lbWelcome;
JLabel lb1, lb2, lb3, lb4, lb5;
JTextField tf1, tf2, tf3, tf4, tf5;
JFrame frame;
GridBagConstraints gbc = new GridBagConstraints();
scramble() {
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
//mainPanel
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBackground(new Color(12, 177, 237));
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 40, 30, 40));
//header/title
lbWelcome = new JLabel("Scramble", SwingConstants.CENTER);
lbWelcome.setFont(mainFont);
lbWelcome.setToolTipText("Scramble is a game created by Glen Filson");
gbc.gridx = 0;
gbc.gridy = 0;
mainPanel.add(lbWelcome, gbc);
//input panel
JPanel inputs = new JPanel();
inputs.setSize(new Dimension(300,300));
inputs.setBackground(new Color(12, 177, 200));
inputs.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 3;
mainPanel.add(inputs, gbc);
gbc.insets = new Insets(30, 10,30,10);
//JLabels main
lb1 = new JLabel("F", SwingConstants.CENTER);
lb1.setFont(smallFont);
gbc.gridx = 0;
gbc.gridy = 0;
inputs.add(lb1, gbc);
lb2 = new JLabel("I", SwingConstants.CENTER);
lb2.setFont(smallFont);
gbc.gridx = 1;
gbc.gridy = 0;
inputs.add(lb2, gbc);
lb3 = new JLabel("G", SwingConstants.CENTER);
lb3.setFont(smallFont);
gbc.gridx = 2;
gbc.gridy = 0;
inputs.add(lb3, gbc);
lb4 = new JLabel("H", SwingConstants.CENTER);
lb4.setFont(smallFont);
gbc.gridx = 3;
gbc.gridy = 0;
inputs.add(lb4, gbc);
lb5 = new JLabel("T", SwingConstants.CENTER);
lb5.setFont(smallFont);
gbc.gridx = 4;
gbc.gridy = 0;
inputs.add(lb5, gbc);
//JTextField main
tf1 = new JTextField("s");
tf1.setFont(smallFont);
tf1.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 0;
gbc.gridy = 1;
inputs.add(tf1, gbc);
tf2 = new JTextField("u");
tf2.setFont(smallFont);
tf2.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 1;
gbc.gridy = 1;
inputs.add(tf2, gbc);
tf3 = new JTextField("s");
tf3.setFont(smallFont);
tf3.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 2;
gbc.gridy = 1;
inputs.add(tf3, gbc);
tf4 = new JTextField("s");
tf4.setFont(smallFont);
tf4.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 3;
gbc.gridy = 1;
inputs.add(tf4, gbc);
tf5 = new JTextField("y");
tf5.setFont(smallFont);
tf5.setHorizontalAlignment(JTextField.CENTER);
gbc.gridx = 4;
gbc.gridy = 1;
inputs.add(tf5, gbc);
//JFrame
JFrame frame = new JFrame();
frame.setTitle("Scramble");
frame.setSize(500, 650);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(new Color(100, 60, 100));
frame.setVisible(true);
frame.add(mainPanel);
}
public static void main(String[] args){
scramble myFrame = new scramble();
}
public class graphicsPanel extends JPanel {
public void paint(Graphics g ){
Graphics g2d = (Graphics2D) g;
g2d.drawRect(250,325,300,300);
}
}
}
There are solutions to everything you asked. So let's see from where to take it.
you can add a border to any JComponent and it's subclasses. Just use setBorder().
To have a JLabel with rectangles around each of the letters, you probably are better off not using a JLabel at all. Subclass JComponent, add a String property so you know which text to render, then override the paintComponent() method. All you need is to loop over the string's characters, calculate the character size via the GraphicsContext and the Font, add space for your box. Then draw the box using g.drawRect(), finally g.drawString().
To organize the position use LayoutMangers. GridBagLayout is the most powerful one and will do anything you require. Check out the nice tutorial.

JFrame center components

I was wondering how to center my components, I found the gridBagLayout but I couldn't find a way to have it bigger than it is : my buttons are too small.
Part of my code :
private void addMainButtons() {
JPanel container = new JPanel() {
private static final long serialVersionUID = -424395301619105440L;
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Dimension dim = this.getSize();
DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.setColor(Color.BLACK);
String s = format.format(date);
g.drawString(s, (int) ((dim.getWidth() - s.length() - 80) / 2), 20);
}
};
container.setBackground(new Color(109, 69, 60));
JButton productsButton = new JButton("Produits");
productsButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
cl.show(frame, pages[1]);
}
});
productsButton.setAlignmentY(Component.CENTER_ALIGNMENT);
productsButton.setAlignmentX(Component.CENTER_ALIGNMENT);
// Creating grid
container.setPreferredSize(new Dimension(400, 600));
container.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
mainPage.setLayout(new BorderLayout());
mainPage.add(container, BorderLayout.CENTER);
// End of main page
}
GridBagLayout is really difficult to use, is there another way to center components ? I could use NestedLayouts but I don't know how.
You can use weightx and/or weighty to effect the amount of space the components will occupy, for example, if I do
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.weightx = 1;
gbc.weighty = 1;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
I can generate this...
You could use two containers, one holding a JLabel which shows the date and one which contains the buttons, but I doubt that's what you're really after.
You can use ipadx and ipady which adds the amount to the components preferred size
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
gbc.ipadx = 40;
gbc.ipady = 40;
container.add(productsButton, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
container.add(new JButton("Entrée"), gbc);
gbc.gridx = 1;
container.add(new JButton("Sortie"), gbc);
which, when included with your existing constraints, allows you to "grow" the buttons a bit.
Try below code for increasing size of button while adding every components to gridbagconstraints. Change the value of weightx/weighty as you want.
gbc.weightx = 1.0;
gbc.weighty = 1.0;
To give more spaces between components, use below code while adding every components to gridbagconstraints.
gbc.insets = new Insets(2, 2, 2, 2);
According to my knowledge, you used correct way to center components. It can also be done by other layout but it may be little bit difficult.

Buttons doesn't fill all available space when I use GridBagLayout in Java

I want to create an application with buttons arrayed into invisible table. The buttons should fill all the available space inside the imaginary cells even when I´ll resize the frame. I´m using Swing, GridBagLayout. I've read some articles and the solution was to add .weightx=1 and .weighty=1. Weightx works perfect and it fill the gaps but weighty doesn't. Buttons don´t extend into height of cell. Is there a problem with my code or is there something to add that solve my problem? Or should I use absolutely another layout?
public class NewClass {
public void NewClass(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
frame.add(panel);
GridBagLayout layout = new GridBagLayout();
panel.setLayout(layout);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JButton B11 = new JButton("11");
panel.add(B11,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
JButton B12 = new JButton("12");
panel.add(B12,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JButton B21 = new JButton("21");
panel.add(B21,gbc);
gbc.gridx = 1;
gbc.gridy = 1;
JButton B22 = new JButton("22");
panel.add(B22,gbc);
frame.pack();
frame.setSize(800,400);
frame.setVisible(true);
}}
You're using the wrong GridBagConstraints#fill field value, since the value you're using is telling the layout manager to fill the buttons horizontally only.
You need to change
gbc.fill = GridBagConstraints.HORIZONTAL;
to
// gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.fill = GridBagConstraints.BOTH;
if you want the buttons to fill both directions, both horizontally and vertically.

Component in JScrollView in GridBagLayout drawn too small

I've got a custom component, derived from JComponent. I'm placing that into a JScrollPane and that into a container using GridBagLayout. Now if the container gets too small, i.e. has to start displaying scroll bars, the component becomes tiny.
The example below renders as follows after starting the application:
But after resizing the frame a bit, it becomes this:
Here is the code:
import java.awt.*;
import javax.swing.*;
class SO26736343 extends JPanel {
#Override public void paintComponent(Graphics g) {
g.setColor(Color.YELLOW);
g.fillRect(0, 0, getWidth(), getHeight());
}
#Override public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
public static void main(String[] args) {
JFrame frm = new JFrame();
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container cp = frm.getContentPane();
cp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
cp.add(new JButton("NW"), gbc);
cp.add(new JButton("N"), gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
cp.add(new JButton("NE"), gbc);
gbc.gridwidth = 1;
cp.add(new JButton("W"), gbc);
cp.add(new JScrollPane(new SO26736343()));
gbc.gridwidth = GridBagConstraints.REMAINDER;
cp.add(new JButton("E"), gbc);
gbc.gridwidth = 1;
cp.add(new JButton("SW"), gbc);
cp.add(new JButton("S"), gbc);
cp.add(new JButton("SE"), gbc);
frm.setSize(500, 500);
frm.setVisible(true);
}
}
I executed this on OS X 10.8.5 with Java 1.7.0_25.
I guess there might be something wrong with my component, but I don't know what. Shouldn't the layout make an attempt to display that component as large as possible, even if it can't be displayed at its preferred size?
I think you forgot to set the constraints when you are adding your custom panel and thus the behavior is unpredictable (or at least unexpected):
gbc.gridwidth = 1;
cp.add(new JButton("W"), gbc);
cp.add(new JScrollPane(new SO26736343())); // gbc missing here
If you want this panel fill all available space, then set both weightx and weighty properties to a value greather than 0 and add your panel using this constraint:
gbc.weightx = 1;
gbc.weighty = 1;
cp.add(new JScrollPane(new SO26736343()), gbc);
Screenshots
This sort of problem happens a lot when I use textfields in Swing. I always set the minimum size of the problem component to its preferred size :
myComponent.setMinimumSize(myComponent.getPreferredSize());
You can also set weight and fill on the gbc.
////////////
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
////////////
This prevents, when the scrollbars kick in, the collapsing effect. Most commonly happens in textfields and text areas.
http://blue-walrus.com/2011/04/swing-textfieldtextarea-collapse-on-dialog-resize/

Align JLabel to the left of the panel in a gridbaglayout

I have a panel in which i have specified with a grid bag layout. I basically have 1 column and 4 rows. The labels are aligned to the center by default. How do i align them to the left?
private void addLabel(String name, int gridx, int gridy, int anchor ){
gbc.gridx=gridx;
gbc.gridy=gridy;
JLabel label=new JLabel(name);
gbc.fill=GridBagConstraints.HORIZONTAL;
gbag.setConstraints(label, gbc);
panel1.add(label);
The caller lines are:
gbc=new GridBagConstraints();
gbag=new GridBagLayout();
panlel1.setLayout(gbag);
addLabel(" Exemption type", 0, 0,anchor );
try
JLabel myLabel = new JLabel("Fubar", SwingConstants.LEFT);
Or you could do the same on an already created JLabel by calling myLabel.setHorizontalAlignment(SwingConstants.LEFT);
edit: for example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.*;
public class GridBagExample {
private static void createAndShowUI() {
String[] data = {"one", "two", "three", "four"};
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0; // **** comment this line out to see effect ****
gbc.weighty = 1.0; // **** comment this line out to see effect ****
for (int i = 0; i < data.length; i++) {
JLabel label = new JLabel(data[i]);
gbc.gridy = i;
panel.add(label, gbc);
}
JFrame frame = new JFrame("GridBagExample");
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Here is how I solved this.
The important part is
gbc.anchor = GridBagConstraints.WEST;
The above is called right after you specify the layout cell you want and right before you add the component to the panel.
GridBagConstraints anchor
This field is used when the component is smaller than its display
area. It determines where, within the display area, to place the
component. ...
Below is basically how I implemented it.
public class ControlPanel extends JPanel{...
ControlPanel(){
this.setLayout(new GridBagLayout());
//create components
...
GridBagConstraints gbc = new GridBagConstraints();
//space components out a little
gbc.insets = new Insets(5,5,5,5);
gbc.gridx = 0;
gbc.gridy = 0;
this.add(button_btn,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(spinner1_pnl,gbc);
gbc.gridx = 2;
gbc.gridy = 0;
this.add(spinner2_pnl,gbc);
gbc.gridx = 3;
gbc.gridy = 0;
this.add(checkbox1_chk,gbc);
gbc.gridx = 4;
gbc.gridy = 0;
this.add(checkbox2_chk,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 3; //span 3 columns
gbc.anchor = GridBagConstraints.WEST;
this.add(results_lbl,gbc);
}
}
In this case I put a label below some other components, but most importantly that label is left (west) aligned within its cell.

Categories