How to align left or right inside GridBagLayout cell? - java

I see that GridBagLayout positions it's children with center alignment within cells. How to align left or right?
UPDATE
Constructing code (I know I could reuse c)
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
// placing controls to dialog
GridBagConstraints c;
GridBagLayout layout = new GridBagLayout();
setLayout(layout);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
add(inputSource_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 0;
add(inputSource_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 1;
add(output_label, c);
c = new GridBagConstraints();
c.gridx = 1;
c.gridy = 1;
add(output_combo, c);
c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 2;
add(button_panel, c);

When using GridBagLayout for a tabular display of JLabel : JTextField, I like to have a method that makes my GridBagConstraints for me based on the x, y position. For example something like so:
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
The following code makes a GUI that looks like this:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
import javax.swing.*;
public class GridBagEg {
private static void createAndShowGui() {
PlayerEditorPanel playerEditorPane = new PlayerEditorPanel();
int result = JOptionPane.showConfirmDialog(null, playerEditorPane,
"Edit Player", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.PLAIN_MESSAGE);
if (result == JOptionPane.OK_OPTION) {
// TODO: do something with info
for (PlayerEditorPanel.FieldTitle fieldTitle :
PlayerEditorPanel.FieldTitle.values()) {
System.out.printf("%10s: %s%n", fieldTitle.getTitle(),
playerEditorPane.getFieldText(fieldTitle));
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
#SuppressWarnings("serial")
class PlayerEditorPanel extends JPanel {
enum FieldTitle {
NAME("Name"), SPEED("Speed"), STRENGTH("Strength");
private String title;
private FieldTitle(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
};
private static final Insets WEST_INSETS = new Insets(5, 0, 5, 5);
private static final Insets EAST_INSETS = new Insets(5, 5, 5, 0);
private Map<FieldTitle, JTextField> fieldMap = new HashMap<FieldTitle, JTextField>();
public PlayerEditorPanel() {
setLayout(new GridBagLayout());
setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("Player Editor"),
BorderFactory.createEmptyBorder(5, 5, 5, 5)));
GridBagConstraints gbc;
for (int i = 0; i < FieldTitle.values().length; i++) {
FieldTitle fieldTitle = FieldTitle.values()[i];
gbc = createGbc(0, i);
add(new JLabel(fieldTitle.getTitle() + ":", JLabel.LEFT), gbc);
gbc = createGbc(1, i);
JTextField textField = new JTextField(10);
add(textField, gbc);
fieldMap.put(fieldTitle, textField);
}
}
private GridBagConstraints createGbc(int x, int y) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.anchor = (x == 0) ? GridBagConstraints.WEST : GridBagConstraints.EAST;
gbc.fill = (x == 0) ? GridBagConstraints.BOTH
: GridBagConstraints.HORIZONTAL;
gbc.insets = (x == 0) ? WEST_INSETS : EAST_INSETS;
gbc.weightx = (x == 0) ? 0.1 : 1.0;
gbc.weighty = 1.0;
return gbc;
}
public String getFieldText(FieldTitle fieldTitle) {
return fieldMap.get(fieldTitle).getText();
}
}
In this example, I display the JPanel in a JOptionPane, but it could just as easily be displayed in a JFrame or JApplet or JDialog or ...

For example
public class DimsPanel extends JPanel
{
public static void main(String[] args){
JFrame main = new JFrame("Dims");
JPanel myPanel = new DimsPanel();
main.setContentPane(myPanel);
main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
main.setSize(400, 400);
main.setLocationRelativeTo(null);
main.setVisible(true);
}
JButton ok_button = new JButton("OK"), cancel_button = new JButton("Cancel");
JLabel inputSource_label = new JLabel("Input source:"),
output_label = new JLabel("Output:");
JComboBox inputSource_combo = new JComboBox(new String[]{"A", "B", "C"}),
output_combo = new JComboBox(new String[]{"A", "B", "C"});
public DimsPanel(){
super(new BorderLayout());
Box main = new Box(BoxLayout.Y_AXIS);
Dimension labelsWidth = new Dimension(100, 0);
JPanel inputPanel = new JPanel(new BorderLayout());
inputSource_label.setPreferredSize(labelsWidth);
inputPanel.add(inputSource_label, BorderLayout.WEST);
inputPanel.add(inputSource_combo);
JPanel outputPanel = new JPanel(new BorderLayout());
output_label.setPreferredSize(labelsWidth);
outputPanel.add(output_label, BorderLayout.WEST);
outputPanel.add(output_combo);
// button panel
JPanel button_panel = new JPanel();
button_panel.add(ok_button);
button_panel.add(cancel_button);
main.add(inputPanel);
main.add(outputPanel);
add(main, BorderLayout.NORTH);
add(button_panel);
}
}
You can run and see it. Resizing works like a charm and the layout code has only 18 lines.
The only disadvantage is that you need to specify the width of the labels by hand. If you really don't want to see setPreferredSize() in the code, then be my guest and go with GridBag. But I personally like this code more.

Related

JFrame is not appearing consistently once JTable was added

I am currently trying to include a JTable to my JPanel. I was not having any problems with my code previously until I started to code the table. Sometimes when I run my program everything will appear, sometimes just the panels appear, and sometimes/majority of the time nothing will appear. I just don't understand why it is not consistent. There are no errors in the console. I have included below my ViewPage.java, Page.java, and Main.java.
`
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class ViewPage extends Page implements ActionListener
{
JPanel panel1, panel2, panel3;
JLabel searchLabel, repairsLabel, dateLabel;
JButton goButton, recentButton, oldestButton, homeButton;
JComboBox dropDown;
JTextField textField;
JTable tabel;
JScrollPane scrollpane;
public ViewPage()
{
panel1 = new JPanel();
panel1.setBackground(Color.blue);
panel1.setBounds(0,0,1280,120);
panel2 = new JPanel();
panel2.setBackground(Color.green);
panel2.setBounds(0,120,1280,480);
panel3 = new JPanel();
panel3.setBackground(Color.red);
panel3.setBounds(0,600,1280,120);
//Panel 1 components
repairsLabel = new JLabel("Repairs");
repairsLabel.setFont(new Font("Serif", Font.BOLD, 50));
searchLabel = new JLabel("Search :");
searchLabel.setFont(new Font("Serif", Font.PLAIN, 25));
goButton = new JButton("GO");
goButton.setFocusable(false);
goButton.addActionListener(this);
textField = new JTextField();
String[] filters = {" ", "customerID", "First_Name", "Last_Name"};
dropDown = new JComboBox(filters);
dropDown.addActionListener(this);
panel1.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 0);
gbc.weightx = 5.5;
gbc.gridx = 0;
gbc.gridy = 0;
panel1.add(repairsLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.5;
gbc.gridx = 1;
gbc.gridy = 0;
panel1.add(searchLabel, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.weightx = 3;
gbc.gridx = 2;
gbc.gridy = 0;
panel1.add(dropDown, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 50);
gbc.gridx = 3;
gbc.gridy = 0;
gbc.ipadx = 100;
panel1.add(textField, gbc);
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(1, 10, 1, 100);
gbc.gridx = 4;
gbc.gridy = 0;
gbc.ipadx = 1;
panel1.add(goButton, gbc);
//Panel 2 components
panel2.setLayout(new GridBagLayout());
String[][] data = new String[50][8];
String[] headings = {"customer_ID", "Date", "First Name", "Last Name", "Phone #", "OS", "PC Type", "Problem"};
JTable table = new JTable(data, headings);
table.setEnabled(false);
table.setPreferredScrollableViewportSize(new Dimension(1000,400));
table.setFillsViewportHeight(true);
scrollpane = new JScrollPane(table);
panel2.add(scrollpane);
//Panel 3 componets
panel3.setLayout(new GridBagLayout());
GridBagConstraints gbc2 = new GridBagConstraints();
dateLabel = new JLabel("Date Filter: ");
dateLabel.setFont(new Font("Serif", Font.PLAIN, 25));
recentButton = new JButton("Most Recent");
oldestButton = new JButton("Oldest");
homeButton = new JButton("Home");
gbc2.fill = GridBagConstraints.HORIZONTAL;
gbc2.insets = new Insets(1, 10, 1, 0);
gbc2.weightx = 5.5;
gbc2.gridx = 0;
gbc2.gridy = 0;
panel3.add(dateLabel, gbc);
frame.add(panel1);
frame.add(panel2);
frame.add(panel3);
}
#Override
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == dropDown)
{
System.out.println(dropDown.getSelectedItem());
}
}
}
`
`
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public abstract class Page
{
private final static int pageWidth = 1280;
private final static int pageHeight = 720;
protected JFrame frame;
public Page()
{
frame = new JFrame();
frame.setTitle("Computer Repair Store");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(pageWidth, pageHeight);
frame.setLayout(null);
frame.setVisible(true);
}
public int getpageWidth()
{
return pageWidth;
}
public int getpageHeight()
{
return pageHeight;
}
}
`
`
public class Main {
public static void main(String[] args) {
ViewPage viewPage = new ViewPage();
}
}
`
Ouput:
enter image description here
This is what I am expecting to output which has only appeared 2-3 times out of the 50 times I have tried running the program.
enter image description here

JFrame Buttons and GridBagConstraints

Why are my constraints for my buttons not working? I looked at the Java Docs and am doing the same thing the tutorials are doing, but for me the buttons stay the same regardless of what gridx, y, width, or fill I use. Any ideas? Here's my code:
class MyWindow
{
public static void main(String [] arg)
{
MyJFrame f = new MyJFrame("My GUI 2015");
f.setVisible(true);
f.setSize(10, 20);
f.add(f.p);
}
}
and
public class MyJFrame extends JFrame {
public JPanel p;
JButton close = new JButton("close");
JButton drawing = new JButton("drawing");
JButton image = new JButton("image");
JButton browser = new JButton("browser");
public MyJFrame(String title) {
super(title);
p = new JPanel();
buildButtons();
}
void buildButtons() {
GridBagConstraints c = new GridBagConstraints();
c.insets = new Insets(0,40,0,150);
c.gridx = 0;
c.gridy = 0;
p.add(drawing, c);
c.gridx = 2;
c.gridy = 0;
p.add(close, c);
c.insets = new Insets(50,225,50,150);
c.gridx = 0;
c.gridy = 1;
p.add(image, c);
c.insets = new Insets(0,125,0,125);
c.gridx = 0;
c.gridy = 100;
c.gridwidth = 3;
c.fill = GridBagConstraints.HORIZONTAL;
p.add(browser, c);
}
}
The LayoutManager for the container is not specified in your current code (the default for a JPanel is FlowLayout). If you wish to use a GridBagLayout on the container, you must explicitly specify the LayoutManager:
p = new JPanel(new GridBagLayout());
//or
p.setLayout(new GridBagLayout());

JPanel: Can not get the width of the JPanel

Please have a look at the following code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TestForm extends JFrame
{
private JLabel firstLabel, secondLabel;
private JTextField firstTxt, secondTxt;
private GridBagLayout mainLayout = new GridBagLayout();
private GridBagConstraints mainCons = new GridBagConstraints();
private JPanel centerPanel;
public TestForm()
{
this.setLayout(mainLayout);
//Declaring instance variables
firstLabel = new JLabel("First: ");
secondLabel = new JLabel("Second: ");
firstTxt = new JTextField(7);
secondTxt = new JTextField(7);
mainCons.anchor = GridBagConstraints.WEST;
mainCons.weightx = 1;
mainCons.gridy = 2;
mainCons.gridx = 1;
mainCons.insets = new Insets(15, 0, 0, 0);
this.add(createCenterPanel(), mainCons);
System.out.println("Center Panel Width: "+centerPanel.getWidth());
this.setTitle("The Test Form");
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenterPanel()
{
centerPanel = new JPanel();
GridBagLayout gbl = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
centerPanel.setLayout(gbl);
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstLabel,gbc);
gbc.gridx = 2;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,0,0,0);
centerPanel.add(firstTxt,gbc);
gbc.gridx = 3;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,10,0,0);
centerPanel.add(secondLabel,gbc);
gbc.gridx = 4;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(15,-10,0,0);
centerPanel.add(secondTxt,gbc);
centerPanel.setBorder(BorderFactory.createTitledBorder("The Testing Form"));
centerPanel.setPreferredSize(centerPanel.getPreferredSize());
centerPanel.validate();
System.out.println("Width is: "+centerPanel.getWidth());
System.out.println("Width is: "+centerPanel.getHeight());
return centerPanel;
}
public static void main(String[]args)
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
new TestForm();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
I am trying to get the width of the centerPanel in 2 places. But in both cases, I get 0 as the answer! I must get the width and height somehow because the southPanel (not included here) will use those values, with some reduce to the height. Please help!
The width is 0 before pack() or setSize() is called. You can get the width and use it after pack() call
or
define your own LayoutManager which use the width for the height of another layout part (southPanel)

How would I be able to achieve this expandable layout in Java? Flexible BoxLayout etc

I would like to be able to have three JPanels p1 p2 and p3, and have them lay out like so:
I have been playing around with FlowLayout, BoxLayout etc but I'm not really sure if I am heading in the right direction. I am quite new with Java so I don't know what does what if I'm quite honest.
I like how BoxLayout works, resizing the panels, but I would like to be able to give it some sort of width attribute.
I am not using a visual designer for this, this is my window code at the moment:
private void initialize() {
Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize();
frame = new JFrame();
frame.setLayout(new GridLayout(1, 3));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(dimensions.width / 2 - WINDOW_WIDTH / 2,
dimensions.height / 2 - WINDOW_HEIGHT / 2,
WINDOW_WIDTH, WINDOW_HEIGHT);
JPanel p1 = new JPanel(new BorderLayout());
p1.setBackground(Color.red);
JPanel p2 = new JPanel(new BorderLayout());
p2.setBackground(Color.black);
JPanel p3 = new JPanel(new BorderLayout());
p3.setBackground(Color.blue);
frame.add(p2);
frame.add(p1);
frame.add(p3);
}
Any pointers appreciated!
EDIT: I have managed to get it to work how I wanted, thanks to mKorbel. The right column isn't laid out exactly as I was going to do it but I actually changed my mind and decided to keep the other layout.
The code:
import java.awt.*;
import javax.swing.*;
public class PanelWindow extends JFrame {
private static final long serialVersionUID = 1L;
private static final int WINDOW_HEIGHT = 600;
private static final int WINDOW_WIDTH = 800;
private JPanel p1, p2, p3;
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
PanelWindow panelWindow = new PanelWindow();
}
});
}
public PanelWindow() {
initialize();
}
private void initialize() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
p1 = new JPanel();
p1.setBackground(Color.red);
p2 = new JPanel();
p2.setBackground(Color.green);
p3 = new JPanel();
p3.setBackground(Color.blue);
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 97;
gbc.insets = new Insets(2, 2, 2, 2);
add(p1, gbc);
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 3;
gbc.insets = new Insets(2, 2, 2, 2);
add(p2, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.gridwidth = 1;
gbc.gridheight = 2;
gbc.weightx = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(p3, gbc);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension dimensions = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(dimensions.width / 2 - WINDOW_WIDTH / 2,
dimensions.height / 2 - WINDOW_HEIGHT / 2,
WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle("Panel Window");
}
}
not my favorite LayoutManager, example by using GridBagLayout, easiest could be to use MigLayout, maybe ...
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "70pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 70;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "30pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 30;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx =1;
gbc.gridy = 0;
gbc.gridwidth = /*gbc.gridheight = */1;
gbc.gridheight = 2;
gbc.weightx = /*gbc.weighty = */20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
One word: MigLayout. As you have seen, it is possible with the standard layout managers. But I can guarantee you, the layout code would be reduced to 4 lines with MigLayout... (Although it would take you some time to get into MigLayout as it works a bit different than the usual layout managers).

Java 2 JPanel's in one JFrame layout

Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.

Categories