GridBagLayout content not aligning to the right of JPanel - java

I have a JFrame (BorderLayout) holding a JPanel(GridBagLayout) in the South position. The JPanel border fills the screen horizontally (as I wanted it to), and so does the content within it (I don't want that).
It's much easier to visualize, so I did in Photoshop what I couldn't figure out in Java...
I made this in photoshop to demonstrate what I WANT to happen:
This is what my code produces:
Here's the code I'm using:
private void loadTags(String filePath)
{
Map<String, ArrayList<String>> fileTags;
try
{
fileTags = PowerPointManipulator.getTagsFromFile(filePath);
}
catch (IOException e)
{
System.err.println("Could not open Powerpoint File");
e.printStackTrace();
return;
}
tag_listener = new TagButtonListener();
pnl_tags = new JPanel();
pnl_tags.setBackground(new Color(0, 0, 0, 0));
pnl_tags.setLayout(new GridBagLayout());
pnl_tags.setAlignmentX(LEFT_ALIGNMENT);
brd_tags = new TitledBorder("Tags");
brd_tags.setTitleColor(Color.WHITE);
brd_tags.setBorder(new LineBorder(Color.WHITE));
pnl_tags.setBorder(brd_tags);
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.insets = new Insets(0, 0, 2, 15);
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
int col = 0;
for (String key : fileTags.keySet())
{
ArrayList<String> vals = fileTags.get(key);
gbc.gridwidth = 2;
gbc.gridx = col;
gbc.gridy = 0;
JToggleButton tempButton = new JToggleButton(key);
tempButton.setOpaque(false);
tempButton.addActionListener(tag_listener);
tempButton.setFocusable(false);
pnl_tags.add(tempButton, gbc);
int row = 1;
for (String val : vals)
{
tempButton = new JToggleButton(val);
tempButton.setOpaque(false);
tempButton.addActionListener(tag_listener);
tempButton.setFocusable(false);
gbc.gridwidth = 1;
gbc.gridy = row;
pnl_tags.add(tempButton, gbc);
row++;
}
col += 2;
}
contentPane.add(pnl_tags, BorderLayout.PAGE_END);
}
If I remove the "weight" options, then I get the proper layout, except that the buttons are centered within the JPanel.
I feel like I'm so close, but I can't get the exact right settings! Any help is much appreciated!

GridBagConstraints#weightx and GridBagConstraints#weighty will cause the component to occupy all the remaining space left over after all the other components have been laid out, GridBagConstraints#fill will cause the component to fill the available space of the cell it resides in based on the value you supply so,
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
is doing exactly what you asked it to.
You could try something like...
List<String> tags = new ArrayList<>(25);
tags.add("example");
tags.add("objective");
tags.add("motivation");
tags.add("summary");
tags.add("c");
tags.add("*");
tags.add("*");
tags.add("*");
tags.add("cs");
JPanel tagPane = new JPanel(new GridBagLayout());
tagPane.setBorder(new TitledBorder("Tags"));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 3;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
for (String tag : tags) {
tagPane.add(new JToggleButton(tag), gbc);
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
}
}
Which results in something like...
Okay, so that's a little better, but they are grouped in the center!
Well, you could set it so each right hand side column has a weightx of 1, for example...
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
gbc.weightx = 1;
} else {
gbc.weightx = 0;
}
Or add a "filler" component to the right of all the other components...
for (String tag : tags) {
tagPane.add(new JToggleButton(tag), gbc);
gbc.gridx--;
if (gbc.gridx < 0) {
gbc.gridx = 3;
gbc.gridy++;
}
}
JLabel filler = new JLabel();
gbc.gridx = 4;
gbc.gridy = 0;
gbc.weightx = 1;
tagPane.add(filler, gbc);
Either way, you end up with something like....
Take a closer look at How to Use GridBagLayout for more details

Related

Why does my gui layout change when uploading a photo?

My programs user interface currently uses a grid bag layout, I want it to be a fixed size however when i upload a picture to the label the whole interface changes in dimensions.
Below is code for my layout manager
public SearchService() throws Exception {
setSize(600, 600);
setResizable(false);
JPanel mainPanel = new JPanel();
JPanel templatePanel = new JPanel();
JPanel toolPanel = new JPanel();
JLabel picLabel = new JLabel();
JLabel tools = new JLabel("Tools");
JLabel templates = new JLabel("Templates");
JButton upload = new JButton("Upload");
JButton search = new JButton("Search");
JButton save = new JButton("Save");
//Main panel
GridBagLayout GBPanel = new GridBagLayout();
GridBagConstraints GBC = new GridBagConstraints();
mainPanel.setLayout( GBPanel );
//Template panel
GBC.gridx = 0;
GBC.gridy = 0;
GBC.gridwidth = 1;
GBC.gridheight = 3;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 1;
GBC.weighty = 0;
GBC.anchor = GridBagConstraints.WEST;
GBPanel.setConstraints( leftPanel, GBC );
leftPanel.add(templates);
mainPanel.add( leftPanel );
//Picture label
GBC.gridx = 1;
GBC.gridy = 0;
GBC.gridwidth = 2;
GBC.gridheight = 1;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 0;
GBC.weighty = 1;
GBC.anchor = GridBagConstraints.CENTER;
GBPanel.setConstraints( picLabel, GBC );
mainPanel.add( picLabel );
//Tool panel
GBC.gridx = 4;
GBC.gridy = 0;
GBC.gridwidth = 1;
GBC.gridheight = 3;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 1;
GBC.weighty = 0;
GBC.anchor = GridBagConstraints.EAST;
GBPanel.setConstraints( rightPanel, GBC );
rightPanel.add(tools);
mainPanel.add( rightPanel );
//Upload button
GBC.gridx = 1;
GBC.gridy = 1;
GBC.gridwidth = 1;
GBC.gridheight = 1;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 1;
GBC.weighty = 0;
GBC.anchor = GridBagConstraints.PAGE_START;
GBPanel.setConstraints( upload, GBC );
mainPanel.add( upload );
//Save button
GBC.gridx = 2;
GBC.gridy = 1;
GBC.gridwidth = 1;
GBC.gridheight = 1;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 1;
GBC.weighty = 0;
GBC.anchor = GridBagConstraints.PAGE_START;
GBPanel.setConstraints( save, GBC );
mainPanel.add( save );
//Search button
GBC.gridx = 1;
GBC.gridy = 2;
GBC.gridwidth = 2;
GBC.gridheight = 1;
GBC.fill = GridBagConstraints.BOTH;
GBC.weightx = 1;
GBC.weighty = 0;
GBC.anchor = GridBagConstraints.PAGE_START;
GBPanel.setConstraints( search, GBC );
mainPanel.add( search );
add(mainPanel);
and below is code that adds the picture
upload.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser("C:\\Users);
FileNameExtensionFilter filter = new FileNameExtensionFilter("Image", "jpg", "png", "bmp");
chooser.setFileFilter(filter);
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = chooser.getSelectedFile();
BufferedImage bi;
userPhoto = chooser.getSelectedFile().getPath();
try {
bi = ImageIO.read(selectedFile);
Image dimg = bi.getScaledInstance(picLabel.getWidth(), picLabel.getHeight(), Image.SCALE_SMOOTH);
picLabel.setIcon(new ImageIcon(dimg));
}
catch(IOException IOe) {
IOe.printStackTrace();
}
System.out.println(userPhoto);
}
}
});
I' ve added two photos to show the results with my program. This is how it looks when i first run and how i want the layout to stay
and this is how layout looks after uploading an image
as you can see the left and right panels get shrunk and the picture doesn't even take up the whole picture label.
I also added this line System.out.println(picLabel.getWidth()); in the action listener and saw that when the button is first hit the size is set to 299 but if i hit the button again it changes and does so for each time. I want to know if its possible to make the image stay at a width of 299.
GBC.gridwidth = 5;
GBC.gridheight = 20
You can't just randomly assign gridwith/height to a component. You actually need 20 other components if you want to component to span the same height as the other components.
as you can see the left and right panels get shrunk and the picture doesn't even take up the whole picture label.
If you don't want the layout to change then use a different layout manager or nested panels with different layout managers.
For example you start with the BorderLayout.
Then you can add panels to the LINE_START and LINE_END.
Then you need another panel in the CENTER. Again you could use a BorderLayout. You add your picture to the CENTER and then another panel with the buttons at the PAGE_END.
Now all the components except the image are fixed in size. The space available to the image will vary depending on the size of the frame.
So the basic code is:
JPanel buttonPanel = new JPanel(...);
JLabel image = new JLabel(...);
JPanel center = new JPanel( new BorderLayout() );
center.add(image, BorderrLayout.CENTER);
center.add(buttonPanel, BorderLayout.PAGE_END);
JPanel leftPanel = new JPanel(...);
JPanel rightPanel = new JPanel(...);
frame.add(leftPanel, BorderLayout.LINE_START);
frame.add(center, BorderLayout.CENTER);
frame.add(rightPanel, BorderLayout.LINE_END);
Far less confusing than trying to play with all the constraints of the GridBagLayout.
Now the child panels (left, right, buttons) can use appropriate layout managers.

GridBagLayout not applying gridy changes

I'm trying to create a personal DnD character sheet program. The main idea is to have 4 large panels that each contain one of the major sections of a basic character sheet. I'm currently working on the first panel that has stats and saving throws. I'm trying to get more comfortable with GridBagLayout while making this, but I've run into a problem with setting gridy. I've already visited the GridBagLayout not obeying gridx and gridy and (unless I'm just stupid), that didn't help me. I used GridBagLayout with GridBagConstraints for statsPanel() and gridy worked fine.
Here's the problem: whenever I set gridy to the next grid in proficinciesAndSkillsPanel(), it's treated like I just changed gridx. My goal is to have one column with many rows, not one row with many columns. Thank you for your time
//this builds the jframe and sets the primary jpanel
private void buildComponents()
{
setSize(800, 600);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mp = (JPanel)getContentPane();
mp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridheight = 1;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 0;
mp.add(panelA(), gbc);
gbc.gridx = 1;
mp.add(new JButton("test"), gbc);
createMenuBar();
setVisible(true);
}
//this creates the first real panel that i'm currently working with
private JPanel panelA()
{
JPanel result = new JPanel();
result.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
//I left out the code for statsPanel() because that works fine
result.add(statsPanel(), gbc);
gbc.gridx = 1;
result.add(proficinciesAndSkillsPanel(), gbc);
return result;
}
//this builds the second half of the upper portion of panel A
private JPanel proficinciesAndSkillsPanel()
{
JPanel result = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1;
gbc.weighty = 1;
result.add(labeledTextField("Inspiration", inspirationField = new JTextField(2), null, 1), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
result.add(labeledTextField("Proficiency bonus", proficiencyField = new JTextField(2), null, 1),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
result.add(labeledRadioField("Strength", strSTField = new JTextField(2), strRB = new JRadioButton()),gbc);
return result;
}
//this creates a JTextField with the appropriate label and a sub-JTextField
private JPanel labeledTextField(String str, JTextField jtf, JTextField bonjtf, int space)
{
JPanel result = new JPanel();
JPanel subResult = new JPanel();
result.setLayout(new FlowLayout());
result.add(new JLabel(str));
result.add(Box.createHorizontalStrut(space));
subResult.add(jtf);
jtf.setHorizontalAlignment(JTextField.CENTER);
try
{
subResult.add(bonjtf);
bonjtf.setHorizontalAlignment(JTextField.CENTER);
bonjtf.setEditable(false);
bonjtf.setText("+0");
}catch(NullPointerException e){}
jtf.addKeyListener(new JTF_Listener(){
public void update() {
String str2 = "";
try
{
int result = (Integer.parseInt(jtf.getText())-10)/2;
if(result >=0)
{
str2 += "+"+Integer.toString(result);
}
else
{
str2 += Integer.toString(result);
}
}catch(NumberFormatException nfe){}
bonjtf.setText(str2);
}
});
result.add(subResult);
return result;
}
//this does the same as labeledTextField, just with a radioButton
private JPanel labeledRadioField(String str, JTextField jtf, JRadioButton jrb)
{
JPanel result = new JPanel();
result.setLayout(new FlowLayout());
result.add(jrb);
result.add(jtf);
result.add(new JLabel(str));
jtf.setHorizontalAlignment(JTextField.CENTER);
jtf.setText("+0");
jtf.addKeyListener(new JTF_Listener(){
public void update(){
String str2 = "";
try
{
int result = Integer.parseInt(jtf.getText());
str2+= "+" + Integer.toString(result);
}catch(NumberFormatException nfe){}
jtf.setText(str2);
}
});
return result;
}
Not sure that this is your problem since you've not posted a valid MCVE (please correct this!), but here:
private JPanel proficinciesAndSkillsPanel()
{
JPanel result = new JPanel(); // ******** here *********
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = 1;
gbc.weighty = 1;
result.add(labeledTextField("Inspiration", inspirationField = new JTextField(2), null, 1), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
result.add(labeledTextField("Proficiency bonus", proficiencyField = new JTextField(2), null, 1),gbc);
gbc.gridx = 0;
gbc.gridy = 2;
result.add(labeledRadioField("Strength", strSTField = new JTextField(2), strRB = new JRadioButton()),gbc);
return result;
}
You're treating this result JPanel as if it uses GridBagLayout when in fact it's not, it's using JPanel's default FlowLayout
One confusing bit: you've got many JPanel variables that have been given the same name, result. In your code you do in fact call result.setLayout(new GridBagLayout()), but not for the JPanel that I show above, and this might be confusing you. I suggest that you avoid using the same variable names in your code as you're doing to avoid this confusion.
If you need more specific help, then you first, please tell us more of the details and show us your pertinent code as a valid minimal example program or MCVE. If you're sitting in our shoes, and are trying to understand someone else's confusing code, it makes a huge difference if they put the effort in to make that code compilable and runnable for us.

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.

How to align JLabel next to a JTextField in a GridBagLayout

My form is very simple I just want to have labels next to text fields. The labels are default centering and it makes the form look weird. I want to the labels exactly next to the textfield. I have played with the horizontal alignment of the labels and textfields but it did not change anything.
Here is my code:
JPanel root = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets= new Insets(0,0,0,0);
newVehicleRecord.setLayout(new BorderLayout());
newVehicleRecord.add(root,BorderLayout.PAGE_START);
JLabel title = new JLabel("New Vehicle Record - Customer ID:" + customerIDInfo.getText());
title.setFont(fontTitle);
gbc.weightx = 0;
gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth= 2;
root.add(title,gbc);
gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth= 1;
root.add(Box.createVerticalStrut(15),gbc);
gbc.gridx = 0; gbc.gridy = 2;
JLabel classificationLabel = new JLabel("Classification:");
classificationLabel.setHorizontalAlignment(JLabel.RIGHT);
root.add(classificationLabel,gbc);
gbc.gridx = 1; gbc.gridy = 2;
JTextField classificationTextField = new JTextField(10);
classificationTextField.setHorizontalAlignment(JTextField.LEFT);
root.add(classificationTextField,gbc);
gbc.gridx = 0; gbc.gridy = 3;
JLabel modelLabel = new JLabel("Model:");
root.add(modelLabel,gbc);
gbc.gridx = 1; gbc.gridy = 3;
JTextField modelTextField = new JTextField(10);
root.add(modelTextField,gbc);
gbc.gridx = 0; gbc.gridy = 4;
JLabel makeLabel = new JLabel("Make:");
root.add(makeLabel,gbc);
gbc.gridx = 1; gbc.gridy = 4;
JTextField makeTextField = new JTextField(10);
root.add(makeTextField,gbc);
I get the following display: http://prntscr.com/6j3iki
As you can see there is a lot of empty space between the label and the textfield which I don't want.
I want to the labels exactly next to the textfield.
You need to play with the anchor constraint:
gbc.anchor = GridBagConstraints.LINE_END;
panel.add(label, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
panel.add(textField, gbc);
Also you would probably want something like:
gbc.insets = new Insets(5, 10, 5, 10);
so the right edge of the label has some space between the left edge of the text field.
Read the section from the Swing tutorial on How to Use GridBagLayout for more information on all the constraints.
Something like this:
gbc.gridx = 0; gbc.gridy = 3;
gbc.anchor = GridBagConstraints.EAST;
JLabel modelLabel = new JLabel("Model:");
root.add(modelLabel,gbc);
So you need to add the line
gbc.anchor = GridBagConstraints.EAST;
to each your label.
Another possibility:
gbc.gridx = 0; gbc.gridy = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
JLabel modelLabel = new JLabel("Model:");
modelLabel.setHorizontalAlignment(SwingConstants.RIGHT);
root.add(modelLabel,gbc);

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