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.
Related
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.
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
I'm trying to create a GridBagLayout, I have got the panels set out exactly how I want them. However I cannot set the background colour of each panel without also forcing all of the components to center.
Here the panels are coloured but all of the components center
http://i.imgur.com/BattBdw.png
Here all of the components snap to NORTHWEST as specified in the code but the background color does not fill the pane.
http://i.imgur.com/lvuEy4u.png
Sorry I cannot embed the pictures, my reputation is not high enough :(
GridBagConstraints GBC = new GridBagConstraints();
GBC.fill = GridBagConstraints.BOTH;
GBC.anchor = GridBagConstraints.NORTHWEST;
//green panel
GBC.gridx = 0;
GBC.gridy = 0;
GBC.weightx = 0.1;
GBC.weighty = 0.1;
JPanel panelGreen = new JPanel();
panelGreen.setBackground(Color.green);
//add button to green panel
JButton button = new JButton("Button");
panelGreen.add(button, GBC);
contentPane.add(panelGreen, GBC);
//blue panel
GBC.gridx = 1;
GBC.gridy = 0;
GBC.weighty = 0.1;
GBC.weightx = 0.9;
JPanel panelBlue = new JPanel();
panelBlue.setBackground(Color.blue);
contentPane.add(panelBlue, GBC);
//red panel
GBC.gridx = 0;
GBC.gridy = 1;
GBC.weighty = 0.8;
GBC.weightx = 0.1;
JPanel panelRed = new JPanel();
panelRed.setBackground(Color.red);
contentPane.add(panelRed, GBC);
//black panel
GBC.gridx = 0;
GBC.gridy = 2;
GBC.weighty = 0.1;
GBC.weightx = 0.1;
GBC.gridwidth =2;
JPanel panelBlack = new JPanel();
panelBlack.setBackground(Color.black);
contentPane.add(panelBlack, GBC);
//yellow panel
GBC.gridx = 1;
GBC.gridy = 1;
GBC.weighty = 0.8;
GBC.weightx = 0.9;
GBC.gridwidth =1;
JPanel panelYellow = new JPanel();
panelYellow.setBackground(Color.yellow);
contentPane.add(panelYellow, GBC);
Firstly, creating a JPanel() with the default constructor means it gets a FlowLayout - you need to tell your panels to use GridBagLayouts:
JPanel panelGreen = new JPanel(new GridBagLayout());
Other than that, you just need to have the "fill" property set to NONE when you add your JButton or it will expand to fill the whole pane. After you've added the button you can set it to BOTH for the panels themselves:
GBC.fill = GridBagConstraints.NONE;
JButton button = new JButton("Button");
panelGreen.add(button, GBC);
GBC.fill = GridBagConstraints.BOTH;
contentPane.add(panelGreen, GBC);
I have to make this for school:
This is the code I have so far:
import javax.swing.*;
import java.awt.*;
public class AddressBookGui1 extends JFrame {
public AddressBookGui1(){
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(gbl);
JLabel label;
JButton button;
JTextField textField;
JTextArea textArea = new JTextArea(10, 20);
gbc.weightx = 1;
label = new JLabel("text");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
add(label ,gbc);
textField = new JTextField();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 0;
add(textField ,gbc);
label = new JLabel("text");
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
add(label ,gbc);
textField = new JTextField();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.gridwidth = 2;
add(textField, gbc);
label = new JLabel("text");
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.gridwidth = 1;
add(label ,gbc);
textField = new JTextField();
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
gbc.gridwidth = 2;
add(textField, gbc);
label = new JLabel("text");
gbc.weightx = 1;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.gridwidth = 1;
add(label ,gbc);
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.gridy = 3;
add(textArea, gbc);
gbc.weightx = 1;
button = new JButton("text");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 4;
add(button ,gbc);
gbc.weightx = 1;
button = new JButton("text");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 4;
add(button ,gbc);
}
public static void main(String[] args){
AddressBookGui1 frame = new AddressBookGui1();
frame.setTitle("Address Book");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
(I still need to deal with padding and insets. I've gotten those to work in a much simpler program so I think I have a handle on that stuff)
I've tried the GridBagLayout Oracle tutorial and I'm not sure what I'm doing wrong. Can someone help me make it look more like it is supposed to? Specifically to make the text fields and text area span over 2 cells.
Few things I noticed about your code.
Do not use setSize() of JFrame. This will cause abnormal behavior.
Instead, let the frame size itself according to the size of its
components. If you want the frame to be bigger, adjust not the size
of the frame but the components inside it. You can either
setpreferredSize or override the getpreferredsize of the component if
you really want to adjust is size since GridBagLayout is one of those layout managers that respects the
preferredSize of the component. Use pack() to remove the unecessary
space.
Do not extend a JFrame, make your UI class to have a main panel and
add all the components there. provide a getter for that panel (e.g.
getUI()) for extracting the UI of that class.
Always reinstantiate the GridBagConstraints object whenever it is
going to be applied to another component. This way it is more
readable.
Use insets to put padding around the component.
Do not reuse same reference to different components;
Use Initial Thread
This is not standard but it I find it really helpful when working
with GridBagLayout, in setting the constraints of gbc, make it in
alphabetical order.
To solve your problem, here is the modified code with the things I pointed out about applied.
public class AddressBook {
private JPanel pnlMain;
public AddressBook() {
pnlMain = new JPanel();
pnlMain.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JLabel lblName = new JLabel("Name");
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0, 10, 0, 0);
gbc.weightx = 1;
pnlMain.add(lblName, gbc);
JTextField txtName = new JTextField();
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 3;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.insets = new Insets(5, 0, 0, 10);
gbc.weightx = 1;
pnlMain.add(txtName, gbc);
JLabel lblPhone = new JLabel("Phone");
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.insets = new Insets(0, 10, 0, 0);
gbc.weightx = 1;
pnlMain.add(lblPhone, gbc);
JTextField txtPhone = new JTextField();
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 3;
gbc.gridx = 1;
gbc.gridy = 1;
gbc.insets = new Insets(5, 0, 0, 10);
gbc.weightx = 1;
pnlMain.add(txtPhone, gbc);
JLabel lblEmail = new JLabel("Email");
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.insets = new Insets(0, 10, 0, 0);
gbc.weightx = 1;
pnlMain.add(lblEmail, gbc);
JTextField txtEmail = new JTextField();
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 3;
gbc.gridx = 1;
gbc.gridy = 2;
gbc.weightx = 1;
gbc.insets = new Insets(5, 0, 0, 10);
pnlMain.add(txtEmail, gbc);
JLabel lblAddress = new JLabel("Address");
gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 3;
gbc.insets = new Insets(0, 10, 0, 0);
gbc.weightx = 1;
pnlMain.add(lblAddress, gbc);
JTextArea txtAreaAddress = new JTextArea(10, 20);
JScrollPane pane = new JScrollPane(txtAreaAddress);
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTH;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 3;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.insets = new Insets(5, 0, 0, 10);
gbc.weightx = 1;
pnlMain.add(pane, gbc);
JButton btnSave = new JButton("Save");
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.NONE;
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 4;
gbc.insets = new Insets(10, 10, 10, 0);
gbc.weightx = 1;
pnlMain.add(btnSave, gbc);
JButton btnCancel = new JButton("Cancel");
gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = 1;
gbc.gridx = 3;
gbc.gridy = 4;
gbc.insets = new Insets(10, 0, 10, 10);
gbc.weightx = 1;
pnlMain.add(btnCancel, gbc);
}
public JPanel getUI(){
return pnlMain;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Address Book");
frame.getContentPane().add(new AddressBook().getUI());
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
gbc.gridwidth is the parameter that allows a component to span more than one column. For example, if you have 3 columns and 4 rows and you want a label to occupy the complete top row, then you need to assign the first cell for the label. and set gbc.gridwidth = 3;
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.