Building a GUI using GridBagLayout (Java) - java

I am trying to build a GUI for a little Java game using a GridBagLayout. Finally it should look like this:
This is my code:
private GridBagConstraints c;
...
c.gridx = 1;
c.gridy = 0;
c.weightx = 0;
add(playButton, c);
c.gridx = 1;
c.gridy = 1;
c.weightx = 0;
add(optionsButton, c);
c.gridx = 1;
c.gridy = 2;
c.weightx = 0;
add(manualButton, c);
c.gridx = 1;
c.gridy = 3;
c.weightx = 0;
add(exitButton, c);
c.gridx = 0;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHWEST;
add(creditsButton, c);
c.gridx = 2;
c.gridy = 4;
c.weightx = 1;
c.anchor = GridBagConstraints.SOUTHEAST;
add(legalNoticeButton, c);
At the moment it looks like this:
My question is who I can set the two buttons to the bottom without setting the four other bottoms to the top?

Something like this is more or less #Gilbert Le Blanc explained (with minor differences):
Basically use another panel to move your two buttons to the south and spread them to WEST and EAST:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
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");
final JPanel centerPanel = new JPanel();
centerPanel.setLayout(new GridBagLayout());
JButton playButton = new JButton("Play");
JButton optionsButton = new JButton("Options");
JButton manualButton = new JButton("Manual");
JButton exitButton = new JButton("Exit");
JButton creditsButton = new JButton("Credits");
JButton legalNoticeButton = new JButton("Legal");
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.REMAINDER;
centerPanel.add(playButton, c);
centerPanel.add(optionsButton, c);
centerPanel.add(manualButton, c);
centerPanel.add(exitButton, c);
JPanel bottomPanel = new JPanel(new BorderLayout());
bottomPanel.add(creditsButton, BorderLayout.WEST);
// Filler component that avoids having the bottom panel too small
bottomPanel.add(new JComponent() {
#Override
public Dimension getPreferredSize() {
return new Dimension(centerPanel.getPreferredSize().width, 0);
}
});
bottomPanel.add(legalNoticeButton, BorderLayout.EAST);
frame.add(centerPanel);
frame.add(bottomPanel, BorderLayout.SOUTH);
frame.pack();
frame.setMinimumSize(frame.getPreferredSize());
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();
}
});
}
}

Related

Put space between label in GridLayout

package committeeGUI;
import static committeeGUI.CommitteeGUI.comList;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class StudentMemberFrame extends JFrame {
public StudentMemberFrame() {
super("Add Student");
setSize(450, 500);
setLocation(561, 150);
super.setResizable(false);
addStudentMember();
}
public void addStudentMember() {
CommitteeGUI.frame.setEnabled(false);
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
//creating border and size of the border
showConsoleArea.setBorder(BorderFactory.createLineBorder(Color.black, 3));
add(showConsoleArea); //, BorderLayout.CENTER);
//setting a size to showConsoleArea.
showConsoleArea.setSize(500, 500);
final JLabel lblheading = new JLabel("STUDENT");
// showConsoleArea.add(lblheading,BorderLayout.CENTER);
/*
* creating components of company form
*/
final JLabel lblCommitteeName = new JLabel("Committee name");
final JTextField txtName = new JTextField(15);
final JLabel lblMemberName = new JLabel("Student name");
final JTextField txtMemberName = new JTextField(15);
final JLabel lblMemberNumber = new JLabel("Student number");
final JTextField txtMemberNumber = new JTextField(15);
final JLabel lblMemberCourse = new JLabel("Student course");
final JTextField txtMemberCourse = new JTextField(15);
final JButton buttAdd = new JButton("SAVE");
final JButton buttCancel = new JButton("CANCEL");
// adding components to the display area
c.gridx = 1;
c.gridy = 0;
showConsoleArea.add(lblheading, c);
c.gridx = 0;
c.gridy = 1;
showConsoleArea.add(lblCommitteeName, c);
c.gridx = 1;
c.gridy = 1;
showConsoleArea.add(txtName, c);
c.gridx = 0;
c.gridy = 2;
showConsoleArea.add(lblMemberName, c);
c.gridx = 1;
c.gridy = 2;
showConsoleArea.add(txtMemberName, c);
c.gridx = 0;
c.gridy = 3;
showConsoleArea.add(lblMemberNumber, c);
c.gridx = 1;
c.gridy = 3;
showConsoleArea.add(txtMemberNumber, c);
c.gridx = 0;
c.gridy = 4;
showConsoleArea.add(lblMemberCourse, c);
c.gridx = 1;
c.gridy = 4;
showConsoleArea.add(txtMemberCourse, c);
c.gridx = 0;
c.gridy = 5;
showConsoleArea.add(buttAdd, c);
c.gridx = 1;
c.gridy = 5;
showConsoleArea.add(buttCancel, c);
/*
* able to displaying the company frame
*/
this.show();
buttAdd.addActionListener((ActionEvent e) -> {
if (txtName.getText().equals("")
|| txtMemberName.getText().equals("")
|| txtMemberNumber.getText().equals("")
|| txtMemberCourse.getText().equals("")) //validating the data
{
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Enter a valid data", 0);
return;
}
if (!txtMemberNumber.getText().matches("\\d+")) {
CommitteeGUI.frame.setEnabled(false);
setEnabled(false);
messagebox("Member number must be a integer", 0);
return;
}
for (Committee com : comList) {
if (com.getName().equals(txtName.getText())) {
Student st = new Student();
st.setName(txtMemberName.getText());
st.setAcademicNo(Integer.parseInt(txtMemberNumber.getText()));
st.setCourse(txtMemberCourse.getText());
com.memberList.add(st);
messagebox("Member added successfully", 1);
setEnabled(false);
return;
}
}
messagebox("No Committee found with given name", 1);
});
//creating ActionListner to Cancel button
buttCancel.addActionListener((ActionEvent e) -> {
//frame is enabled for user.
CommitteeGUI.frame.setEnabled(true);
dispose(); //disposing the frame
} //pass the action to actionPerformed method and perform it.
);
}
#SuppressWarnings("deprecation")
public void messagebox(String label, final int conform) {
final JDialog infoBox = new JDialog();//message box
infoBox.setSize(400, 90);
infoBox.setAlwaysOnTop(true);
infoBox.setResizable(false);
infoBox.setLocation(675, 258);
JLabel space = new JLabel(" ");
JLabel label1 = new JLabel(label);
JButton buttOk = new JButton("Ok");
buttOk.addActionListener((ActionEvent e) -> {
if (conform == 1) {
// making frame operation enable.
CommitteeGUI.frame.setEnabled(true);
dispose();
}
setEnabled(true);
infoBox.hide();
});
JPanel holder = new JPanel(new FlowLayout());
holder.add(label1);
holder.add(buttOk);
infoBox.add(holder);
infoBox.show();
}
}
Above is my code. I want to put space between the heading (STUDENT) and the fields.
Attached is the snapshot of the frame:
I am not familiar with this layout. Help is much appreciated.
public void addStudentMember() {
final JPanel showConsoleArea = new JPanel(new FlowLayout(FlowLayout.LEFT));
showConsoleArea.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
// Add below line of code change appropriate spacing
c.insets = new Insets(10, 10, 10, 10);

Getting rid of extra spaces between components when the JFrame is resized

I am using the GridBagLayout to arrange some components in a frame.
When the frame is first created, the components have a decent space in between them.
But as soon as I resize the frame there are alot of unwanted space between the components
I tried adjusting the weights and insets as suggested by some users, but it does not seem to fix the problem
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JTextArea;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
GridBagConstraints c = new GridBagConstraints();
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
menuBar.add(menu);
c.gridx = 0;
c.gridy = 0;
c.gridwidth = c.REMAINDER;
c.fill = c.HORIZONTAL;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(menuBar, c);
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(one, c);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(oneF, c);
c.gridx = 0;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(two, c);
c.gridx = 1;
c.gridy = 2;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(twoF, c);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(three, c);
c.gridx = 1;
c.gridy = 3;
c.gridwidth = 1;
c.fill = c.NONE;
c.gridheight = 1;
c.weightx = 1;
c.weighty = 1;
c.anchor = c.NORTH;
c.insets = new Insets(5,5,5,5);
add(threeF, c);
//setResizable(false);
pack();
setVisible(true);
}
}
ps:- I am new to GUI programming, so please forgive me for any noob mistakes.
edit 1: This is the what I want to have after I am done. I know the currently it does not look anyway near what I have in mind... I am still working on it
Thanks
use an nested layout (combinations of a few LayoutManagers), your picture talks me about,
still you can use GridBagLayout for components placed into left side,
in my code (simplest idea as is possible) JComponents placed on left side can't be resizable because are restricted from LayoutManager`s defaults, more in Oracle tutorial
.
.
painted from SSCCE/MCVE
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MyFrame {
private static final long serialVersionUID = 1L;
private JFrame myFrame = new JFrame("Whatever");
private JPanel parentPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(600, 400);
}
#Override
public Color getBackground() {
return new Color(255, 000, 000);
}
};
private JPanel leftPanel = new JPanel(/*default is FlowLayout*/) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 000);
}
};
private JPanel leftChildPanel = new JPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 400);
}
#Override
public Color getBackground() {
return new Color(255, 255, 225);
}
};
private JPanel rightPanel = new JPanel(new BorderLayout(10, 10)) {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 380);
}
#Override
public Color getBackground() {
return new Color(000, 255, 225);
}
};
public MyFrame() {
parentPanel.add(leftPanel, BorderLayout.WEST);
leftPanel.add(leftChildPanel);
parentPanel.add(rightPanel);
myFrame.add(parentPanel);
myFrame.setLocation(150, 150);
myFrame.pack();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
new MyFrame();
});
}
}
The idea is to add empty row / columns that will grow to fill the available space:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
public class Frame1 extends JFrame {
JLabel one = new JLabel("one");
JLabel two = new JLabel("two");
JLabel three = new JLabel("three");
JTextField oneF = new JTextField(20);
JTextField twoF = new JTextField(20);
JTextField threeF = new JTextField(20);
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("menu");
public Frame1() {
setTitle("GridBagLayout Test");
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.rowHeights = new int[]{0, 0, 0, 0}; //this defines 4 rows
//make 2 last empty row grow
gridBagLayout.rowWeights = new double[]{0.0, 0.0, 1.0,1.0};
//do the same for columns
gridBagLayout.columnWidths = new int[]{0, 0, 0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, 1.0,1.0};
getContentPane().setLayout(gridBagLayout);
menuBar.add(menu);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 5;
c.fill = c.HORIZONTAL;
c.anchor = c.NORTH;
c.insets = new Insets(5, 5, 5, 0);
getContentPane().add(menuBar, c);
//better have a new GridBagConstraints for each component added
GridBagConstraints c1 = new GridBagConstraints();
c1.gridx = 0;
c1.gridy = 1;
c1.gridwidth = 1;
c1.fill = c1.NONE;
c1.anchor = c1.NORTH;
c1.insets = new Insets(5, 5, 0, 5);
getContentPane().add(one, c1);
GridBagConstraints c2 = new GridBagConstraints();
c2.gridx = 1;
c2.gridy = 1;
c2.fill = c2.NONE;
c2.anchor = GridBagConstraints.NORTHWEST;
c2.insets = new Insets(5, 5, 0, 5);
getContentPane().add(oneF, c2);
pack();
setVisible(true);
}
public static void main(String[] args) {
new Frame1();
}
}
EDIT: in response to your edit: use the additional "growing" column for the "cover art"
The problem is your assignments of c.weightx and c.weighty. weightx and weighty determine how extra space is allocated to grid cells in a GridBagLayout when the container is made larger than necessary to accommodate the preferred sizes of the components.
The weightx and weighty should be zero for all cells except those cells which you want to grow larger when the window is made larger.
I have no real idea on how it is supposed to look like, but you could try to set for the labels c.anchor=GridBagConstraints.EAST and c.anchor=GridBagConstraints.WEST for the textfields.
Try also setting c.fill = GridBadConstraints.BOTH.

How do I create spacing in between JButtons?

I am trying to create little main menu for a simple scheduling program right now, but I am having a bit of difficulty having some space in between the buttons. They just stick right next to each other, I would like there to be a gap between each button.
I have tried to use the weightx, weighty commands but nothing seems to change.
I would like to have some blank space between the edges of the GUI and the sides of the buttons, and also between each button.
Here's a screenshot
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
public class Scheduler {
JButton VDay, VWeek, Task, Exit;
JFrame wframe, dframe, tframe;
JLabel head;
public void CreateFrame() {
JFrame frame = new JFrame("Main Menu");
ButtonListener btnlst = new ButtonListener();
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
head = new JLabel("The Plain Scheduler");
panel.add(head, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 1;
c.gridheight = 2;
c.gridwidth = 3;
VDay = new JButton("View Day");
panel.add(VDay, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 3;
VWeek = new JButton("View Week");
panel.add(VWeek,c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 5;
c.gridheight = 2;
c.gridwidth = 3;
Task = new JButton("Assign/Edit Tasks");
panel.add(Task, c);
c.weightx = 1;
c.weighty = .25;
c.gridx = 0;
c.gridy = 7;
c.gridheight = 1;
c.gridwidth = 2;
Exit = new JButton("Exit");
panel.add(Exit, c);
VDay.addActionListener(btnlst);
VWeek.addActionListener(btnlst);
Task.addActionListener(btnlst);
Exit.addActionListener(btnlst);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
Scheduler scheduler = new Scheduler();
scheduler.CreateFrame();
}
}
You can use GridBagConstraints#insets to define the amount of spacing/padding which is added to a cell, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Scheduler {
JButton VDay, VWeek, Task, Exit;
JFrame wframe, dframe, tframe;
JLabel head;
public void CreateFrame() {
JFrame frame = new JFrame("Main Menu");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.weightx = 1;
c.weighty = .25;
c.insets = new Insets(5, 0, 5, 0);
c.gridwidth = GridBagConstraints.REMAINDER;
c.fill = GridBagConstraints.BOTH;
head = new JLabel("The Plain Scheduler");
panel.add(head, c);
VDay = new JButton("View Day");
panel.add(VDay, c);
VWeek = new JButton("View Week");
panel.add(VWeek, c);
Task = new JButton("Assign/Edit Tasks");
panel.add(Task, c);
Exit = new JButton("Exit");
panel.add(Exit, c);
frame.add(panel);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Scheduler scheduler = new Scheduler();
scheduler.CreateFrame();
}
});
}
}

How to put a background image on GridBagLayout

I am trying to work with layout managers for the first time, and they are just kicking me in the teeth. I am trying to make a background image and then put buttons on top, using GridBagLayout, if there is a a better layoutmanager please do tell. As for trying to learn how to use layout managers, its very difficult and any learning references would also be much appreciated.
This is what it looks like currently,
I can get the frame to show the full image, but when i use gridlayout manager, it does that
public void addComponentsToPane(Container pane){
BackgroundImage image = new BackgroundImage();
JButton button1, button2, button3, button4, button5;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if(shouldFill){
c.fill = GridBagConstraints.NONE;
}
button1 = new JButton("Button 1");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
button1.setOpaque(false);
pane.add(button1, c);
button2 = new JButton("Button 2");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 0;
c.gridy = 0;
button2.setOpaque(false);
pane.add(button2, c);
button3 = new JButton("Button 3");
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;
c.gridx = 2;
c.gridy = 0;
button3.setOpaque(false);
pane.add(button3, c);
button4 = new JButton("Long-Named Button 4");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 40; //make this component tall
c.weightx = 0.0;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
pane.add(button4, c);
button5 = new JButton("button 1");
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 0; //reset to default
c.weighty = 1.0; //request any extra vertical space
c.anchor = GridBagConstraints.PAGE_END; //bottom of space
c.insets = new Insets(10,0,0,0); //top padding
c.gridx = 1; //aligned with button 2
c.gridwidth = 2; //2 columns wide
c.gridy = 2; //third row
pane.add(button5, c);
c.ipadx = 800;
c.ipady = 400;
pane.add(image, c);
}
This is what i'm trying to make it look like
Here is one way to do it: using a JLabel as a container with an image (it's a bit unusual but actually works pretty well):
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class TestBackgroundImage {
private static final String BACKHGROUND_IMAGE_URL = "http://www.okyn.org/wp-content/uploads/2013/04/League_of_Legends.jpeg";
protected void initUI() throws MalformedURLException {
JFrame frame = new JFrame(TestBackgroundImage.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageIcon backgroundImage = new ImageIcon(new URL(BACKHGROUND_IMAGE_URL));
JLabel mainPanel = new JLabel(backgroundImage) {
#Override
public Dimension getPreferredSize() {
Dimension size = super.getPreferredSize();
Dimension lmPrefSize = getLayout().preferredLayoutSize(this);
size.width = Math.max(size.width, lmPrefSize.width);
size.height = Math.max(size.height, lmPrefSize.height);
return size;
}
};
mainPanel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
gbc.weightx = 1.0;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
for (int i = 0; i < 5; i++) {
mainPanel.add(new JButton("Button " + (i + 1)), gbc);
}
// Let's put a filler bottom component that will push the rest to the top
gbc.weighty = 1.0;
mainPanel.add(Box.createGlue(), gbc);
frame.add(mainPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
new TestBackgroundImage().initUI();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
And the result:
GridBagLayout is unable to handle layering of components (so if you have overlapping gridx/gridy pairs, it won't handle it as layering, I would think that the output is pretty much undetermined.
Try to avoid using gridx/gridy as it make a code hard to maintain. Playing with relative values on gridwidth/gridheight is much easier to maintain.
Check out the Background Panel for a couple of solutions depending on your requirement:
Use a JLabel for painting the image at its actual size.
Use the BackgroundPanel to allow for scaling of the background image.

Aligning panels with GridBagLayout

I'm not exactly new to java (I've been using it for a year now) but this is my first go at swing. I'm trying to make a very simple chat client to learn both socket and swing at once. My question is "What must I do to align my panels correctly?". I've tried a lot of things (Though I don't have it in my code). Usually I work something like this out on my own, but I'm to the point I need to ask for help. Do I need to change the wieghtx, weighty? What I want the client to look like is something like this.
This is what it currently looks like.
Here is my code.
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
GridBagConstraints c = new GridBagConstraints();
//Main Panel
JPanel window = new JPanel();
window.setLayout(new GridBagLayout());
window.setBackground(Color.black);
//Panels
JPanel display = new JPanel();
JPanel chat = new JPanel();
chat.setLayout(new GridBagLayout());
JPanel users = new JPanel();
display.setBackground(Color.blue);
c.gridx = 0;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(display, c);
chat.setBackground(Color.red);
c.gridx = 0;
c.gridy = 3;
c.gridheight = 2;
c.gridwidth = 1;
c.insets= new Insets(5,5,5,5);
window.add(chat, c);
users.setBackground(Color.green);
c.gridx = 2;
c.gridy = 0;
c.insets= new Insets(5,5,5,5);
window.add(users, c);
//Buttons
//Text fields
JTextArea text = new JTextArea("DEREADFADSFEWFASDFSADFASDF");
c.gridx = 0;
c.gridy = 0;
chat.add(text);
JTextField input = new JTextField("type here to chat", 50);
c.gridx = 0;
c.gridy = 1;
c.insets= new Insets(5,5,5,5);
chat.add(input);
add(window);
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
}
If you wanted something like this as an output :
You can take help from this code example, though you can remove the last ButtonPanel if you don't need that :
package to.uk.gagandeepbali.swing.messenger.gui;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JTextField;
public class ChatPanel extends JPanel
{
private JButton backButton;
private JButton exitButton;
private JButton sendButton;
private JTextPane chatPane;
private JTextPane namePane;
private JTextField chatField;
private GridBagConstraints gbc;
private final int GAP = 10;
private final int SMALLGAP = 1;
public ChatPanel()
{
gbc = new GridBagConstraints();
}
protected void createGUI()
{
setOpaque(true);
setBackground(Color.WHITE);
setLayout(new BorderLayout(5, 5));
JPanel centerPanel = new JPanel();
centerPanel.setOpaque(true);
centerPanel.setBackground(Color.WHITE);
centerPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
centerPanel.setLayout(new GridBagLayout());
gbc.gridx = 0;
gbc.gridy = 0;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
chatPane = new JTextPane();
JScrollPane scrollerChat = new JScrollPane();
scrollerChat.setBorder(BorderFactory.createTitledBorder("Chat"));
scrollerChat.setViewportView(chatPane);
centerPanel.add(scrollerChat, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
namePane = new JTextPane();
JScrollPane scrollerName = new JScrollPane(namePane);
scrollerName.setBorder(BorderFactory.createTitledBorder("Names"));
centerPanel.add(scrollerName, gbc);
gbc.gridx = 0;
gbc.gridy = 5;
gbc.gridwidth = 5;
gbc.weightx = 0.8;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.HORIZONTAL;
chatField = new JTextField();
chatField.setOpaque(true);
chatField.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createTitledBorder("")
, BorderFactory.createEmptyBorder(SMALLGAP, SMALLGAP, SMALLGAP, SMALLGAP)));
centerPanel.add(chatField, gbc);
gbc.gridx = 5;
gbc.gridwidth = 2;
gbc.weightx = 0.2;
sendButton = new JButton("Send");
sendButton.setBorder(BorderFactory.createTitledBorder(""));
centerPanel.add(sendButton, gbc);
JPanel bottomPanel = new JPanel();
bottomPanel.setOpaque(true);
bottomPanel.setBackground(Color.WHITE);
bottomPanel.setBorder(
BorderFactory.createTitledBorder(""));
bottomPanel.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
buttonPanel.setOpaque(true);
buttonPanel.setBackground(Color.WHITE);
buttonPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP));
backButton = new JButton("Back");
exitButton = new JButton("Exit");
buttonPanel.add(backButton);
buttonPanel.add(exitButton);
bottomPanel.add(buttonPanel, BorderLayout.CENTER);
add(centerPanel, BorderLayout.CENTER);
add(bottomPanel, BorderLayout.PAGE_END);
}
public JTextPane getChatPane()
{
return chatPane;
}
public JTextPane getNamePane()
{
return namePane;
}
public JTextField getChatField()
{
return chatField;
}
public JButton getExitButton()
{
return exitButton;
}
public JButton getBackButton()
{
return backButton;
}
public JButton getSendButton()
{
return sendButton;
}
}
What you could do, and probably gives the desired result
JPanel somethingHere = ...;
JPanel chat = ...;
JPanel userList = ...;
JPanel leftPanel = new JPanel( new BorderLayout() );
leftPanel.add( somethingHere, BorderLayout.CENTER );
leftPanel.add( chat, BorderLayout.SOUTH );
JPanel total = new JPanel( new BorderLayout() );
total.add( leftPanel, BorderLayout.CENTER );
total.add( userList, BorderLayout.EAST );
Way simpler then messing with GridBagLayout
Here is what I came out with thus far. The red box is where I plan to add a simple 2D avatar interface with LWJGL.
Here is the code for it
package com.client.core;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class Window extends JFrame{
private int screenWidth = 800;
private int screenHeight = 600;
public Window(){
//Initial Setup
super("NAMEHERE - Chat Client Alpha v0.0.1");
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(screenWidth,screenHeight);
//Main Panels
JPanel window = new JPanel(new BorderLayout());
JPanel center = new JPanel(new BorderLayout());
JPanel right = new JPanel(new BorderLayout());
//Panels
JPanel display = new JPanel( new BorderLayout());
display.setBackground(Color.red);
JPanel chat = new JPanel();
chat.setLayout(new BoxLayout(chat, BoxLayout.Y_AXIS));
chat.setBackground(Color.blue);
JPanel users = new JPanel(new BorderLayout());
users.setBackground(Color.green);
//TextFields
JTextArea chatBox = new JTextArea("Welcome to the chat!", 7,50);
chatBox.setEditable(false);
JTextField chatWrite = new JTextField();
JScrollPane userList = new JScrollPane();
JTextField userSearch = new JTextField(10);
userList.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
users.add(userList);
users.add(userSearch, BorderLayout.NORTH);
chat.add(chatBox);
chat.add(chatWrite);
chat.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1));
//Menu bar
JMenuBar menu = new JMenuBar();
JMenu file = new JMenu("File");
JMenuItem exit = new JMenuItem("Exit");
JMenuItem ipconnect = new JMenuItem("Connect to IP");
file.add(ipconnect);
file.add(exit);
menu.add(file);
//Main window adding
right.add(users);
center.add(display, BorderLayout.CENTER);
center.add(chat, BorderLayout.SOUTH);
window.add(center, BorderLayout.CENTER);
window.add(right, BorderLayout.EAST);
window.add(menu, BorderLayout.NORTH);
add(window);
//Listeners
chatWrite.addKeyListener(new KeyLis());
ipconnect.addActionListener(new ActLis());
exit.addActionListener(new ActLis());
}
static class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER){
System.out.println("Message recieved.");
}
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
static class ActLis implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand() == "Exit"){
System.exit(0);
} else if(e.getActionCommand() == "Connect to IP"){
System.out.println("Connecting....");
JFrame frameip = new JFrame();
JPanel panelip = new JPanel();
JButton buttonip = new JButton("Hello");
frameip.add(panelip);
panelip.add(buttonip);
JDialog ippop = new JDialog(frameip, "Enter IP", false);
}
}
}
}
I had to build a similar layout using a GridBagLayout. The code below shows how I achieved it.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutTest {
public GridBagLayoutTest() {
JFrame jframe = new JFrame();
jframe.setLayout(new GridBagLayout());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(800, 600);
jframe.setVisible(true);
// Left
JPanel leftPanel = new JPanel(new GridBagLayout());
leftPanel.setBackground(Color.YELLOW);
GridBagConstraints gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .7f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 0;
jframe.add(leftPanel, gridBagConstraints);
JPanel leftTopPanel = new JPanel(new FlowLayout());
leftTopPanel.setBackground(Color.RED);
GridBagConstraints gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .7f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 0;
leftPanel.add(leftTopPanel, gridBagConstraints0);
JPanel leftMiddlePanel = new JPanel(new FlowLayout());
leftMiddlePanel.setBackground(Color.BLACK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .2f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 1;
leftPanel.add(leftMiddlePanel, gridBagConstraints0);
JPanel leftBottomBottomPanel = new JPanel(new FlowLayout());
leftBottomBottomPanel.setBackground(Color.PINK);
gridBagConstraints0 = new GridBagConstraints();
gridBagConstraints0.fill = GridBagConstraints.BOTH;
gridBagConstraints0.weightx = 1f;
gridBagConstraints0.weighty = .1f;
gridBagConstraints0.gridx = 0;
gridBagConstraints0.gridy = 2;
leftPanel.add(leftBottomBottomPanel, gridBagConstraints0);
// Right
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.GREEN);
gridBagConstraints = new GridBagConstraints();
gridBagConstraints.fill = GridBagConstraints.BOTH;
gridBagConstraints.weightx = .3f;
gridBagConstraints.weighty = 1f;
gridBagConstraints.gridx = 1;
gridBagConstraints.gridy = 0;
jframe.add(rightPanel, gridBagConstraints);
}
public static void main (String args[]) {
new GridBagLayoutTest();
}

Categories

Resources