GridBagLayout Not Working Properly? - java

I am using a GridBagLayout for my components in a JFrame. I just started using it, and I keep confusing myself. What I want is; Patch notes in the top left, buttons (vertical) on the right, play button on the bottom. I'm not sure what the issue really is, but can you please help me organize this?
Here's my code:
package counter.main;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
public class HomeFrame {
private static JPanel panel;
private static JButton play = new JButton("Play");
private static JPanel p;
File patch = new File(Main.class.getResource("/counter/res/ResourceCounterPatchNotes.txt").getFile());
//private static JLabel text;
public static JLabel greet = new JLabel("", SwingConstants.CENTER);
static JFrame frame = new JFrame("Resource Counter - Home"); {
frame.setSize(800, 500);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.repaint();
frame.revalidate();
createView();
}
private void createView() {
setIcon();
panel = new JPanel();
frame.getContentPane().add(panel);
p = new JPanel();
frame.getContentPane().add(p);
p.setLayout(new FlowLayout(FlowLayout.CENTER, 400, 360));
play.setPreferredSize(new Dimension(200, 70));
p.add(play);
JPanel p2 = new JPanel();
frame.getContentPane().add(p2);
p2.setLayout(new GridBagLayout());
JButton button = new JButton(" Button ");
play.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
try {
Thread.sleep(500);
} catch(InterruptedException ex) {
Thread.currentThread().interrupt();
}
SelectionFrame.frame1.setVisible(true);
frame.setVisible(false);
}
});
JTextArea ta = new JTextArea();
p2.setBackground(Color.BLACK);
ta.setForeground(Color.WHITE);
ta.setFont(new Font("Lucida Sans", Font.PLAIN, 12));
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.insets = new Insets(-150, 5, 5, 30);
gbc.gridx = 0;
gbc.gridy = 0;
p2.add(ta, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
p2.add(button, gbc);
/*gbc.anchor = GridBagConstraints.SOUTH;
gbc.gridx = 0;
gbc.gridy = 2;
p2.add(play, gbc);*/
try {
ta.read(new FileReader(patch), null);
ta.setEditable(false);
//p2.add(ta, BorderLayout.WEST);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
greet.setFont(new Font( "Dialog", Font.BOLD, 20));
frame.getContentPane().add(greet, BorderLayout.NORTH);
}
public void setIcon() {
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(Main.class.getResource("/counter/res/Iron-Pickaxe-icon.png")));
}
}
Here is what I get:

Your code is a mess (sorry), I could spent a lot of time trying to unravel your compound layouts, but it would be easier to just start again. Not saying that you might not consider using a compound layout concept, but I think that's what's got you into such a mess to start with...
So I've basically create a simplified example of what I "guess" your description is asking for...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = gbc.REMAINDER;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.BOTH;
JTextArea patch = new JTextArea(10, 20);
add(new JScrollPane(patch), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
for (int index = 0; index < 6; index++) {
add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.SOUTH;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JButton("Play >"), gbc);
}
}
}
With layouts, it's best to start with pen and paper, group the elements you need to together (like the buttons down the right side for example) and devise a plan for how you might lay them out and prototype of view ideas...
Updated
1) How can I have it so that there is space between the TextArea and the buttons, and vertical space on the buttons? I tried using the Insets but I haven't arranged the numbers in a correct way yet.
insets is the correct way to go...
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(2, 8, 2, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (int index = 0; index < 6; index++) {
core.add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
2) I would like the "Play" button at the center-bottom of the screen, and have it be larger
You "could" do this with GridBagLayout, but I decided not to, as it can cause some issues if you're not careful with how your setup the constraints for the other components, so instead, I used a combination of BorderLayout and GridBagLayout.
To make the "play" button larger, you could modify the font or adjust the button's margins...
playButton.setMargin(new Insets(12, 12, 12, 12));
depending on the effect you're after
public class TestPane extends JPanel {
public TestPane() {
setLayout(new BorderLayout(0, 4));
JPanel core = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridheight = GridBagConstraints.REMAINDER;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
JTextArea patch = new JTextArea(10, 20);
core.add(new JScrollPane(patch), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(2, 8, 2, 4);
gbc.anchor = GridBagConstraints.NORTH;
for (int index = 0; index < 6; index++) {
core.add(new JButton("Button #" + index), gbc);
gbc.gridy++;
}
add(core);
JButton playButton = new JButton("Play >");
playButton.setMargin(new Insets(12, 12, 12, 12));
add(playButton, BorderLayout.SOUTH);
}
}

Related

Java Swing - GridBagConstraints insets color

I'm having some troubles working with GridBagConstraints, specifically with the insets property.
I have two components, and I want some custom margin between theme. Now, what I did was using constraints.insets in this way:
polinomioConstraints.insets = new Insets(5, 0, 15 ,0);
checkboxesPanel.add(infoAggiunte, polinomioConstraints);
checkBoxesPanel.add(anotherString, constraintWithoutInsets);
The problem is that for some reason a white block appears in the insets area, so between the two components, and I found no way to change that white color to the actual panel's background
Here's a GUI I just did for someone else. I added the yellow background.
I don't see white in between the Swing components.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class MainRegistrationPage {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new MainRegistrationPage();
}
});
}
private JTextField firstname;
private JTextField lastname;
private JTextField email;
private JPasswordField password;
private JFrame frame;
public MainRegistrationPage() {
// create user interface
frame = new JFrame("Registration Page");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createRegistrationPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createRegistrationPanel() {
JPanel mainPanel = new JPanel(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
mainPanel.setBackground(Color.YELLOW);
Font font = new Font("Georgia", Font.PLAIN, 14);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 1;
gbc.insets = new Insets(5, 5, 5, 5);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel label = new JLabel("First Name:");
label.setFont(font);
mainPanel.add(label, gbc);
gbc.gridx++;
firstname = new JTextField(30);
firstname.setFont(font);
mainPanel.add(firstname, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Last Name:");
label.setFont(font);
mainPanel.add(label, gbc);
gbc.gridx++;
lastname = new JTextField(30);
lastname.setFont(font);
mainPanel.add(lastname, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Email:");
label.setFont(font);
mainPanel.add(label, gbc);
gbc.gridx++;
email = new JTextField(30);
email.setFont(font);
mainPanel.add(email, gbc);
gbc.gridx = 0;
gbc.gridy++;
label = new JLabel("Password:");
label.setFont(font);
mainPanel.add(label, gbc);
gbc.gridx++;
password = new JPasswordField(30);
password.setFont(font);
mainPanel.add(password, gbc);
gbc.gridwidth = 2;
gbc.gridx = 0;
gbc.gridy++;
JButton submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
}
});
mainPanel.add(submit, gbc);
return mainPanel;
}
}

Align label and combo box in vertical instead of horizontal in java

How do I get my label and combo box to appear vertical instead of horizontal in java? I tried setting the layout to null but it hides the label.
public PetrolApplication()
{
setLayout(new FlowLayout());
add(label);
add(label2);
Combo1 = new JComboBox(Arraycities);
Combo1.setBounds(50, 50, 100, 20);
Use a different layout manager - see A Visual Guide to Layout Managers
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add( new JLabel("I'm assuming you want something"), gbc);
gbc.anchor = GridBagConstraints.LINE_END;
gbc.gridy = 1;
gbc.gridwidth = 1;
add(new JLabel("Please make a selection"), gbc);
DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
model.addElement("This is not what you are looking for");
model.addElement("This is something else");
model.addElement("Not what you think");
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx++;
add(new JComboBox<String>(model));
}
}
}

Java GridBagLayout Aligning buttons

I have a problem with GridbagLayout; I've 5 buttons and I want to have them in this way:
I've already tried different approaches but no one works in the correct way.
For example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGridBagLayout {
protected void initUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel southPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 2;
gbc.gridy = 0;
JButton enterRoom = new JButton("Enter room");
JButton exitRoom = new JButton("Exit room");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton whoIsIn = new JButton("Who is in");
gbc.gridx = 1;
southPanel.add(enterRoom, gbc);
gbc.gridx = 5;
southPanel.add(exitRoom, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
southPanel.add(login, gbc);
gbc.gridx = 3;
southPanel.add(logout, gbc);
gbc.gridx = 6;
southPanel.add(whoIsIn, gbc);
frame.add(southPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGridBagLayout().initUI();
}
});
}
}
Appears:
I'm not interested in other approaches (such as GridLayout), I'd like to know what I'm missing.
GridBagLayout can be a strange animal in some cases. But anyway, gridwidth is something that works, only if there is an actual component that requires some width within the "spanned" column (for example, if you say gridx=0 and gridwidth=2, column 0 has a component and the "spanned" column is column 1).
In your case, column 2, 4 & 7 have no components, so their width is set to 0. Additionnaly, column 5 also gets a width of 0, because column 6 provides enough witdth to the exit room button, so in the end you get the result you see.
Now, not sure of the kind of layout you are trying to achieve (I saw your screenshot, but how should it behave when the panel collapses/expands in width?). So find below, an example that comes a bit closer to what you describe (although I don't find it very nice)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestGridBagLayout2 {
protected void initUI() {
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel southPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = 0;
JButton enterRoom = new JButton("Enter room");
JButton exitRoom = new JButton("Exit room");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton whoIsIn = new JButton("Who is in");
gbc.gridx = 0;
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.EAST;
southPanel.add(enterRoom, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 2;
southPanel.add(exitRoom, gbc);
gbc.gridy = 1;
gbc.gridx = 0;
southPanel.add(login, gbc);
gbc.weightx = 0;
gbc.gridx = 1;
southPanel.add(logout, gbc);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = 2;
southPanel.add(whoIsIn, gbc);
frame.add(southPanel);
frame.pack();
frame.setSize(frame.getWidth() * 4 / 3, frame.getHeight());
frame.setMinimumSize(frame.getSize());
frame.setVisible(true);
}
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException,
UnsupportedLookAndFeelException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGridBagLayout().initUI();
}
});
}
}
GridbagLayout seems to require a row where a component occupies all of the columns in the row. See: Why does this GridBagLayout not appear as planned? for the basis of this solution.
Note the that horizontal strut size was choosen to be half the size of the "Logout" button so that two cells with span the width of the logout button to give the centering of components that you desire.
import java.awt.*;
import javax.swing.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
JButton enterRoom = new JButton("Enter room");
JButton exitRoom = new JButton("Exit room");
JButton login = new JButton("Login");
JButton logout = new JButton("Logout");
JButton whoIsIn = new JButton("Who is in");
setLayout( new GridBagLayout() );
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(5, 0,5, 0);
gbc.gridwidth = 2;
gbc.gridx = 1;
gbc.gridy = 0;
add(enterRoom, gbc);
gbc.gridx = 5;
gbc.gridy = 0;
add(exitRoom, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(login, gbc);
gbc.gridx = 3;
gbc.gridy = 1;
add(logout, gbc);
gbc.gridx = 6;
gbc.gridy = 1;
add(whoIsIn, gbc);
// Add dummy components so every cell has a component.
gbc.insets = new Insets(0, 0, 0, 0);
gbc.gridwidth = 1;
gbc.gridy = 2;
int strutWidth = logout.getPreferredSize().width / 2;
for (int i = 0; i < 8; i++)
{
gbc.gridx = i;
add(Box.createHorizontalStrut(strutWidth), gbc);
}
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE(), BorderLayout.NORTH);
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}

Prevent components from spreading apart when resizing using GridBagLayout

Edit: Each time I try adding the gui tag, it switches to user-interface. Someone mind explaining/fixing that?
I want the client to be resizable. I want the JSeparator to fill the frame's width when resizing, but I want the JLabels to stay next to the fields.
It starts out like this, which the JLabels are too far apart from the fields as it is:
When I resize it horizontally, this is the result:
Which is obviously way too far apart. The code that I use to set up these components are:
public class LoginPanel extends JPanel {
private JTextField userfield = new JTextField(10);
private JPasswordField passfield = new JPasswordField(10);
private JButton login = new JButton("Login");
private JButton create = new JButton("Create Account");
public LoginPanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
gbc.gridx = 2;
JLabel label = new JLabel("Username: ");
add(label, gbc);
gbc.gridx = 3;
gbc.gridwidth = 2;
add(userfield, gbc);
gbc.gridy = 1;
add(passfield, gbc);
gbc.gridx = 2;
label = new JLabel("Password: ");
add(label, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridy = 2;
gbc.gridx = 1;
gbc.gridwidth = 5;
add(new JSeparator(JSeparator.HORIZONTAL), gbc);
}
}
(Had to cut out a few things, please tell me if I'm missing anything)
I've tried anchoring, but I'm still not 100% familiar with GridBagLayout (and the constraints) yet, so I'm not sure if I'm my attempts are in the right direction.
How would I prevent the Username: and Password: labels from moving away from my fields, with still being able to resize?
Also, I want to use GridBagLayout. There is still a lot of things I need to add, and I do not want to use a simple layout due to the fact that I'm going to need flexibility.
Make use of GridBagConstraints#anchor
import java.awt.BorderLayout;
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.JPasswordField;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LogInTest {
public static void main(String[] args) {
new LogInTest();
}
public LogInTest() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new LoginPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class LoginPanel extends JPanel {
private JTextField userfield = new JTextField(10);
private JPasswordField passfield = new JPasswordField(10);
private JButton login = new JButton("Login");
private JButton create = new JButton("Create Account");
public LoginPanel() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1;
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
JLabel label = new JLabel("Username: ");
add(label, gbc);
gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 3;
gbc.gridwidth = 2;
add(userfield, gbc);
gbc.gridy = 1;
add(passfield, gbc);
gbc.anchor = GridBagConstraints.EAST;
gbc.gridx = 2;
label = new JLabel("Password: ");
add(label, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridy = 2;
gbc.gridx = 1;
gbc.gridwidth = 5;
add(new JSeparator(JSeparator.HORIZONTAL), gbc);
}
}
}
You may also want to consider making use of compound layouts, that is, separate each area into it's own container and focus on the individual layout needs for each section and then build them all up into a single layout

how to maintain dimension size of jpanel with GridBagLayout?

Here is my code. When I resize the program the other layouts, it works fine except for the CheckPanel (with GridBagLayout); somehow it became bigger. How can I handle this?
Advance Thanks.
JPanel CheckPanel = new JPanel();
CheckPanel.setBackground(Color.WHITE);
GridBagConstraints gbc_CheckPanel = new GridBagConstraints();
gbc_CheckPanel.gridwidth = 2;
gbc_CheckPanel.fill = GridBagConstraints.BOTH;
gbc_CheckPanel.gridx = 0;
gbc_CheckPanel.gridy = 1;
CenterPanel.add(CheckPanel, gbc_CheckPanel);
CheckPanel.setLayout(new GridLayout(0, 6, 0, 0));
The constraint
gbc_CheckPanel.fill = GridBagConstraints.BOTH;
tells the GridBagLayout to let this component use any available extra space (also depending on its preferred- and maximum size). Using GridBagConstraints.NONE or GridBagConstraints.VERTICAL could solve this, but you still have to decide which component will receive the extra space.
EDIT: Based on the comments, it is still not clear how the other components are inserted, and how the distribution of extra space is specified. In this example, the weighty fields are used to say that the table should receive all extra space. Maybe it helps to identify differences to the original program:
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class CheckboxConstraints
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel centerPanel = new JPanel(new GridBagLayout());
centerPanel.setBackground(Color.RED);
fill(centerPanel);
f.getContentPane().setLayout(new GridLayout(1,1));
f.getContentPane().add(centerPanel);
f.setSize(500, 300);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static void fill(JPanel centerPanel)
{
addSearchBar(centerPanel);
addCheckBoxPanel(centerPanel);
addTable(centerPanel);
}
private static void addSearchBar(JPanel centerPanel)
{
GridBagConstraints gbc = null;
gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0;
gbc.weighty = 0;
centerPanel.add(new JButton("Search"), gbc);
gbc = new GridBagConstraints();
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.weighty = 0;
centerPanel.add(new JTextField(), gbc);
}
private static void addCheckBoxPanel(JPanel centerPanel)
{
JPanel checkPanel = new JPanel();
checkPanel.setBackground(Color.WHITE);
GridBagConstraints gbc_CheckPanel = new GridBagConstraints();
gbc_CheckPanel.gridwidth = 2;
gbc_CheckPanel.fill = GridBagConstraints.BOTH;
gbc_CheckPanel.gridx = 0;
gbc_CheckPanel.gridy = 1;
gbc_CheckPanel.weighty = 0;
centerPanel.add(checkPanel, gbc_CheckPanel);
checkPanel.setLayout(new GridLayout(0, 6, 0, 0));
checkPanel.add(new JCheckBox("C0"));
checkPanel.add(new JCheckBox("C1"));
checkPanel.add(new JCheckBox("C2"));
checkPanel.add(new JCheckBox("C3"));
checkPanel.add(new JCheckBox("C4"));
checkPanel.add(new JCheckBox("C5"));
}
private static void addTable(JPanel centerPanel)
{
JTable table = new JTable(new Object[][] {
{"C00", "C01" },
{"C00", "C01" },
}, new Object[]{ "H0", "H1" });
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weighty = 1.0;
JScrollPane scrollPane = new JScrollPane(table);
centerPanel.add(scrollPane, gbc);
}
}
Please try:
gbc_CheckPanel.fill =GridBagConstraints.HORIZONTAL
and to adjust the space vertically
gbc_CheckPanel.ipady = 20; //Not sure this works in your case but this should fix the resizing issue
Another solution is to add a new JPanel with BorderLayout and insert the panel with JCheckBoxes using the constraint BorderLayout.NORTH and the table with constraint BorderLayout.CENTRE

Categories

Resources