I simply cannot get my JTextFields to align correctly. Right now the program looks like this:
.
Now the Assignment numbers are correctly aligned. However the Mark JTextfield starts under 7 and Weight JTextField starts under the last Mark.
Now what I want is for everything to correctly align. Meaning at Assignment 1 there are Mark and Weight JTextFields under the same row. This should go along all the way down to 7 ( or how many number of rows I choose).
Code:
public class test{
private static final Insets normalInsets = new Insets(10,10,0,10);
private static final Insets finalInsets = new Insets(10,10,10,10);
private static JPanel createMainPanel(){
GridBagConstraints gbc = new GridBagConstraints();
//Adding the JPanels. Panel for instructions
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
//JLabel for the Instructions
JTextArea instructionTextArea = new JTextArea(5, 30);
instructionTextArea.setEditable(false);
instructionTextArea.setLineWrap(true);
instructionTextArea.setWrapStyleWord(true);
JScrollPane instructionScrollPane = new JScrollPane(instructionTextArea);
addComponent(panel, instructionScrollPane, 0, gridy++, 3, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabels for Assignment
JLabel label1 = new JLabel("Assignment");
label1.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label1, 0, gridy, 1, 1, finalInsets,GridBagConstraints.CENTER,GridBagConstraints.HORIZONTAL);
//JLabel for Mark
JLabel label2 = new JLabel("Mark");
label2.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label2, 1, gridy, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabel for Weight.
JLabel label3 = new JLabel("Weight");
label3.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, label3, 2, gridy++, 1, 1, finalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
mark.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, mark, 1, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
//JTextfield for Weight
for(int i=0; i<7; i++){
JTextField weight = new JTextField(20);
weight.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, weight, 2, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
return panel;
}
private static void addComponent(Container container, Component component, int gridx, int gridy, int gridwidth, int gridheight, Insets insets, int anchor, int fill ){
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy, gridwidth, gridheight, 1.0D,1.0D,anchor,fill,insets,0,0);
container.add(component,gbc);
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setVisible(true);
new test();
}
}
I'm a terrible new Java programmer so go easy please :).
UPDATE~~~~~
After running the `for` loops which add the `JLabels` and `JTextFields`, you will need to reset `gbc.gridy = 1`. This way the loop will start adding components from the top row.
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
gbc.gridy = 1;
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
mark.setHorizontalAlignment(JLabel.CENTER);
gridy = 1; //The code only partly works when I include this
addComponent(panel, mark, 1, gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
gbc.gridy = 1;
And this is what it looks like:
Only the Weight JTextField properly aligned. When I don't add 'gridy=1' it has the same format error as my original screenshot.
After running the for loops which add the JLabels and JTextFields, you will need to reset gbc.gridy = 2. This way the loop will start adding components from the top row. Also, in each use of addComponent(), change gridy++ to gbc.gridy++.
gbc.gridy = 2;
//JLabel Number for the number list of assignments at the side.
for(int i = 1; i<=7; i++){
String kok = String.valueOf(i);
JLabel number = new JLabel(kok);
number.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, number, 0, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL);
}
gbc.gridy = 2;
//JTextfield for Mark
for(int i=0; i<7; i++){
JTextField mark = new JTextField(20);
addComponent(panel, mark, 1, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
gbc.gridy = 2;
//JTextfield for Weight
for(int i=0; i<7; i++){
JTextField weight = new JTextField(20);
weight.setHorizontalAlignment(JLabel.CENTER);
addComponent(panel, weight, 2, gbc.gridy++, 1, 1, normalInsets, GridBagConstraints.CENTER,GridBagConstraints.NONE);
}
This is what the result looks like:
Related
For a school project I want to create a GUI which displays a few statistics of a server. I want to use a GridBagLayout to designate boxes to different statistics. The following picture is what I want the GUI layout to be
But when I run my code it looks like this:
The text should fill their area with the background colour and be in their designated area depicted in the first picture.
This is the code I am using:
package Monitoring;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MonitoringGui extends JFrame implements ActionListener {
private Configuratie config;
private MonitoringPanel mp;
public MonitoringGui(Configuratie config) {
this.config = config;
setTitle("MonitoringGui");
setSize(850, 600);
setLayout(new GridBagLayout());
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
// onderdelen toevoegen en verwijderen
JPanel selectorPanel = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
selectorPanel.setBorder(BorderFactory.createLineBorder(Color.black));
addElement(selectorPanel, 0, 0, 4, 2, 0.2, 1, new int[]{20, 20, 20, 20});
// output en input area
JPanel drawArea = new JPanel();
selectorPanel.setLayout(new GridBagLayout());
drawArea.setBackground(Color.lightGray);
addElement(drawArea, 5, 0, 10, 1, 1, 1, new int[]{20, 0, 0, 20});
// buttons, etc
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new GridBagLayout());
addElement(buttonPanel, 5, 1, 10, 1, 1, 0.2, new int[]{0, 0, 20, 20});
//grafiek area
JPanel grafiekArea = new JPanel();
grafiekArea.setLayout(new GridBagLayout());
grafiekArea.setBackground(Color.CYAN);
grafiekArea.add(new JLabel("GrafiekArea"));
addElement(grafiekArea, 0, 0, 3, 1, 1, 0, new int[]{20, 20, 20, 20}, drawArea);
//beschikbaar area
JPanel beschArea = new JPanel();
beschArea.setLayout(new GridBagLayout());
beschArea.setBackground(Color.ORANGE);
beschArea.add(new JLabel("BeschArea"));
addElement(beschArea, 0, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//uptime area
JPanel uptimeArea = new JPanel();
uptimeArea.setLayout(new GridBagLayout());
uptimeArea.setBackground(Color.RED);
uptimeArea.add(new JLabel("UptimeArea"));
addElement(uptimeArea, 2, 1, 1, 1, 0, 0, new int[]{20, 20, 20, 20}, drawArea);
//schijfruimte area
JPanel schijfruimteArea = new JPanel();
schijfruimteArea.setLayout(new GridBagLayout());
schijfruimteArea.setBackground(Color.GREEN);
schijfruimteArea.add(new JLabel("Schijfruimte"));
addElement(schijfruimteArea, 3, 1, 1, 1, 0.2, 0.2, new int[]{20, 20, 20, 20}, drawArea);
setVisible(true);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
add(comp, c);
}
public void addElement(Component comp, int x, int y, int width, int height, double weightx, double weighty, int[] insets, JPanel panel) {
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = x;
c.gridy = y;
c.gridheight = height;
c.gridwidth = width;
c.weightx = weightx;
c.weighty = weighty;
c.insets = new Insets(insets[0], insets[1], insets[2], insets[3]);
panel.add(comp, c);
}
}
I figured out the answer. To make this layout work for my application I have to specify the size of the different panels inside each panel. These are the lines of code I had to add:
selectorPanel.setPreferredSize(new Dimension(120,600));
drawArea.setPreferredSize(new Dimension(660, 600));
grafiekArea.setPreferredSize(new Dimension(670,400));
beschArea.setPreferredSize(new Dimension(220,200));
uptimeArea.setPreferredSize(new Dimension(220,200));
schijfruimteArea.setPreferredSize(new Dimension(220,200));
putting a JPanel in a JFrame: setContentPane() and add() both seem to work. Is there any technical difference?
One example from web has the following. Changing frame.setContentPane(panel) to frame.add(panel) seems to produce the same behavior.
//file: Calculator.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Calculator extends JPanel implements ActionListener {
GridBagConstraints gbc = new GridBagConstraints();
JTextField theDisplay = new JTextField();
public Calculator() {
gbc.weightx = 1.0; gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.BOTH;
ContainerListener listener = new ContainerAdapter() {
public void componentAdded(ContainerEvent e) {
Component comp = e.getChild();
if (comp instanceof JButton)
((JButton)comp).addActionListener(Calculator.this);
}
};
addContainerListener(listener);
gbc.gridwidth = 4;
addGB(this, theDisplay, 0, 0);
// make the top row
JPanel topRow = new JPanel();
topRow.addContainerListener(listener);
gbc.gridwidth = 1;
gbc.weightx = 1.0;
addGB(topRow, new JButton("C"), 0, 0);
gbc.weightx = 0.33;
addGB(topRow, new JButton("%"), 1, 0);
gbc.weightx = 1.0;
addGB(topRow, new JButton("+"), 2, 0 );
gbc.gridwidth = 4;
addGB(this, topRow, 0, 1);
gbc.weightx = 1.0; gbc.gridwidth = 1;
// make the digits
for(int j=0; j<3; j++)
for(int i=0; i<3; i++)
addGB(this, new JButton("" + ((2-j)*3+i+1) ), i, j+2);
// -, x, and divide
addGB(this, new JButton("-"), 3, 2);
addGB(this, new JButton("x"), 3, 3);
addGB(this, new JButton("\u00F7"), 3, 4);
// make the bottom row
JPanel bottomRow = new JPanel();
bottomRow.addContainerListener(listener);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("0"), 0, 0);
gbc.weightx = 0.33;
addGB(bottomRow, new JButton("."), 1, 0);
gbc.weightx = 1.0;
addGB(bottomRow, new JButton("="), 2, 0);
gbc.gridwidth = 4;
addGB(this, bottomRow, 0, 5);
}
void addGB(Container cont, Component comp, int x, int y) {
if ((cont.getLayout() instanceof GridBagLayout) == false)
cont.setLayout(new GridBagLayout());
gbc.gridx = x; gbc.gridy = y;
cont.add(comp, gbc);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("C"))
theDisplay.setText("");
else
theDisplay.setText(theDisplay.getText()
+ e.getActionCommand());
}
public static void main(String[] args) {
JFrame frame = new JFrame("Calculator");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 250);
frame.setLocation(200, 200);
frame.setContentPane(new Calculator());
frame.setVisible(true);
}
}
Another has the following. Changing frame.add(panel) to frame.setContentPane(panel) seems to produce the same behavior.
import javax.swing.*;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class recMod {
public enum RecFieldNames {
FIRST_NAME("First Name:"),
LAST_NAME("Last Name:"),
VENDOR("Vendor:"),
VENDOR_LOC_CODE("Vendor Location Code:"),
USER_EMAIL("User Email Address:"),
USER_NAME("Username:"),
PASSWORD("Password:"),
USER_CODE("User Code:");
private String name;
private RecFieldNames(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
private static final int FIELD_COLS = 7;
private Map<RecFieldNames, JTextField> recFieldMap =
new HashMap<RecFieldNames, JTextField>();
//JButton[] recButtons = new JButton[3];
public recMod() {
JFrame frame = new JFrame("Record Modify");
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
addLabelField(panel, RecFieldNames.FIRST_NAME, 0, 0, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.LAST_NAME, 2, 0, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.EAST);
addLabelField(panel, RecFieldNames.VENDOR, 0, 1, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.VENDOR_LOC_CODE, 2, 1, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_EMAIL, 0, 2, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_NAME, 0, 3, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.CENTER);
addLabelField(panel, RecFieldNames.PASSWORD, 2, 3, 1, 1,
GridBagConstraints.CENTER, GridBagConstraints.WEST);
addLabelField(panel, RecFieldNames.USER_CODE, 0, 4, 1, 1,
GridBagConstraints.WEST, GridBagConstraints.WEST);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
//frame.getContentPane().setPreferredSize(new Dimension(500, 400));
((JComponent) frame.getContentPane()).
setBorder(BorderFactory.createEmptyBorder(30, 30, 30, 30));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public String getFieldText(RecFieldNames rfn) {
return recFieldMap.get(rfn).getText();
}
private void addLabelField(JPanel p, RecFieldNames recFieldNames, int x,
int y, int width, int height, int labelAlign, int fieldAlign) {
GridBagConstraints gbc = new GridBagConstraints();
JLabel label = new JLabel(recFieldNames.getName());
JTextField textField = new JTextField(FIELD_COLS);
recFieldMap.put(recFieldNames, textField);
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = width;
gbc.gridheight = height;
gbc.weightx = 1.0;
gbc.weighty = 0.0;
int midInset = (x == 2) ? 40 : 5;
gbc.insets = new Insets(5, midInset, 5, 5);
gbc.anchor = labelAlign;
gbc.fill = GridBagConstraints.HORIZONTAL;
p.add(label, gbc);
gbc.gridx = x + 1;
gbc.anchor = fieldAlign;
gbc.insets = new Insets(5, 5, 5, 5);
p.add(textField, gbc);
}
public static void main(String args[]) {
new recMod();
}
}
The content pane of the frame is a JPanel.
So if you use frame.add( another panel ), then you have a structure like:
- JFrame
- content pane
- another panel
If you use frame setContentPane( another panel ) you have:
- JFrame
- another panel
See the section from the Swing tutorial on Adding Components to the Content Pane.
I am using GridBagLayout to locate components on panel but it is not working like it has to be. Location of components is not affecting by changing x and y values somebody please help explain what mistake i am making here Thanks in advance :)
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.*;
public class LMS extends JFrame {
JPanel mainPanel;
JLabel RegNum, Name, FatherNam, MotherNam, DateBirth, BloodGrp, Email, Gender, RegDate, Desig, photo;
JTextField RegNuumText, FatherNamText, MotherNamText, EmailText, DesigText;
JList BloodGrpList;
JSpinner DateSpi;
// Constructor
public LMS() {
this.setTitle("Library Managment System");
this.setVisible(true);
this.setSize(700, 600);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
// this.setResizable(false);
mainPanel = new JPanel();
// GridBagLayout bag = new GridBagLayout();
mainPanel.setLayout(new GridBagLayout());
// Creating Labels
RegNum = new JLabel("Registration Number");
Name = new JLabel("Full Name");
FatherNam = new JLabel("Father's Name");
MotherNam = new JLabel("Mother's Name");
DateBirth = new JLabel("Date Of Birth");
BloodGrp = new JLabel("Blood Group");
Email = new JLabel("Email");
Gender = new JLabel("Gender");
RegDate = new JLabel("Registration Date");
Desig = new JLabel("Designation");
photo = new JLabel("Photo");
// creating Text Fields
RegNuumText = new JTextField(30);
FatherNamText = new JTextField();
MotherNamText = new JTextField();
EmailText = new JTextField();
DesigText = new JTextField();
// mainPanel.add(RegNum);
addComp(mainPanel, RegNum, 0, 0, 2, 1, GridBagConstraints.EAST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 0, 1, 2, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
this.add(mainPanel);
}
private void addComp(JPanel thePanel, JComponent comp, int xPos,
int yPos, int compWidth, int compHeight, int place, int stretch) {
GridBagConstraints gridConstraints = new GridBagConstraints();
gridConstraints.gridx = xPos;
gridConstraints.gridy = yPos;
gridConstraints.gridwidth = compWidth;
gridConstraints.gridheight = compHeight;
gridConstraints.weightx = 1;
gridConstraints.weighty = 1;
gridConstraints.insets = new Insets(5, 5, 5, 5);
gridConstraints.anchor = place;
gridConstraints.fill = stretch;
thePanel.add(comp, gridConstraints);
}
public static void main(String[] args) {
new LMS();
}
}
GridBagLayout is not the easiest one, you have to play a little with it. Maybe these lines help you to achieve what you wanted. They will put the label in the upper left corner and the Textfield right behind it.
Note, that there are panels defined as place holders - they will fill the empty space.
addComp(mainPanel, RegNum, 0, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, RegNuumText, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE);
addComp(mainPanel, new JPanel(), 2, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL);
addComp(mainPanel, new JPanel(), 0, 2, 1, 1, GridBagConstraints.WEST, GridBagConstraints.VERTICAL);
You also need to change your helper method a little:
gridConstraints.weightx = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.VERTICAL ? 0 : 1;
gridConstraints.weighty = stretch == GridBagConstraints.NONE || stretch == GridBagConstraints.HORIZONTAL ? 0 : 1;
I think this should do the trick. Maybe you should define two or three helper methods, so you don't need to set all parameters every time. From my experience, very rarely you will need to define the anchor and only some times you might want to stretch components. Most of the time, for me, it is just puting stuff into the right bags (x, y, sometimes: width, height).
Edit: maybe it would help to put setVisible() at the end of the definition, not the beginning.
i have GridBagLayout where I add a JLabel, a JTextfield. But it come out with unpredictable range
Source
public void siswa(){
panel_siswa = new JPanel(); //The Panel
panel_siswa.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(0, 0, 0, 0);
gbc.anchor = GridBagConstraints.CENTER;
label = new JLabel("CEK NILAI");
label.setFont(new Font("Arial", Font.BOLD, 18));
label_id = new JLabel("ID :");
label_name = new JLabel("Name :");
label_id2 = new JLabel("");
label_name2 = new JLabel("");
label_semester = new JLabel("Semester :");
label_semester2 = new JLabel("");
label_jurusan = new JLabel("Jurusan :");
label_jurusan2 = new JLabel("");
label_nilai1 = new JLabel(MP1);
label_nilai2 = new JLabel(MP2);
label_nilai3 = new JLabel(MP3);
label_nilai4 = new JLabel(MP4);
label_nilai5 = new JLabel(MP5);
tf_nilai1 = new JTextField();
tf_nilai2 = new JTextField();
tf_nilai3 = new JTextField();
tf_nilai4 = new JTextField();
tf_nilai5 = new JTextField();
send = new JButton("Send to my email");
gbc.weightx = 0.0;
gbc.gridwidth = 4;
gbc.gridx = 1;
gbc.gridy = 0;
panel_siswa.add(label,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridwidth = 1;
panel_siswa.add(label_id,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 1;
panel_siswa.add(label_id2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 1;
panel_siswa.add(label_jurusan,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = 1;
panel_siswa.add(label_jurusan2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 2;
panel_siswa.add(label_name, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 2;
panel_siswa.add(label_name2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 2;
panel_siswa.add(label_semester,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 4;
gbc.gridy = 2;
panel_siswa.add(label_semester2,gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 4;
panel_siswa.add(label_nilai1, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 4;
panel_siswa.add(tf_nilai1, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 5;
panel_siswa.add(label_nilai2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 5;
panel_siswa.add(tf_nilai2, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 6;
panel_siswa.add(label_nilai3, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 6;
panel_siswa.add(tf_nilai3, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 7;
panel_siswa.add(label_nilai4, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 7;
panel_siswa.add(tf_nilai4, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 1;
gbc.gridy = 8;
panel_siswa.add(label_nilai5, gbc);
gbc.weightx = 0.5;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 3;
gbc.gridy = 8;
panel_siswa.add(tf_nilai5, gbc);
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridy++;
panel_siswa.add(send);
}
}
Output
Problem Statement
I was expecting it will come out like picture below but its not. i think i have a problem on the source.
Question
is my source about gridbaglayout already great ? how to design it properly ?
You create a GUI like this with nested JPanels. Each JPanel can use the layout manager that's best suited for the particular JPanel.
Here's the GUI:
I created a main JPanel to hold all of the subordinate JPanels. The main JPanel uses a BoxLayout, page orientation.
The JPanel that holds the title uses a FlowLayout.
The JPanel that holds the student information uses a GridBagLayout.
The JPanel that holds the MP information uses a different GridBagLayout.
The JPanel that holds the submit button uses a FlowLayout.
Here's the code. This is what is meant by a short, self-contained, runnable example of the solution.
package com.ggl.testing;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class StudentDataEditor implements Runnable {
private static final Insets normalInsets = new Insets(10, 10, 0, 10);
private static final Insets topInsets = new Insets(30, 10, 0, 10);
private Student student;
public static void main(String[] args) {
SwingUtilities.invokeLater(new StudentDataEditor());
}
public StudentDataEditor() {
this.student = new Student("00000017108", "Sutandi",
"Information Systems", 2);
}
#Override
public void run() {
JFrame frame = new JFrame("Student Data Editor");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
panel.add(createTitlePanel());
panel.add(createStudentPanel());
panel.add(createMPPanel());
panel.add(Box.createVerticalStrut(30));
panel.add(createEmailPanel());
panel.add(Box.createVerticalStrut(10));
return panel;
}
private JPanel createTitlePanel() {
JPanel panel = new JPanel();
JLabel titleLabel = new JLabel("CEK NILAI");
titleLabel.setFont(titleLabel.getFont().deriveFont(24F));
panel.add(titleLabel);
return panel;
}
private JPanel createStudentPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel idLabel = new JLabel("ID:");
addComponent(panel, idLabel, 0, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField idTextField = new JTextField(15);
idTextField.setEditable(false);
idTextField.setText(student.getId());
addComponent(panel, idTextField, 1, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel jurusanLabel = new JLabel("Jurusan:");
addComponent(panel, jurusanLabel, 2, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField jurusanTextField = new JTextField(15);
jurusanTextField.setEditable(false);
jurusanTextField.setText(student.getJurusan());
addComponent(panel, jurusanTextField, 3, gridy++, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel nameLabel = new JLabel("Name:");
addComponent(panel, nameLabel, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField nameTextField = new JTextField(15);
nameTextField.setEditable(false);
nameTextField.setText(student.getName());
addComponent(panel, nameTextField, 1, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel semesterLabel = new JLabel("Semester:");
addComponent(panel, semesterLabel, 2, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField semesterTextField = new JTextField(15);
semesterTextField.setEditable(false);
semesterTextField.setText(Integer.toString(student.getSemester()));
addComponent(panel, semesterTextField, 3, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return panel;
}
private JPanel createMPPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
int gridy = 0;
JLabel mp1Label = new JLabel("MP1");
addComponent(panel, mp1Label, 0, gridy, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp1TextField = new JTextField(25);
addComponent(panel, mp1TextField, 1, gridy++, 1, 1, topInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp2Label = new JLabel("MP2");
addComponent(panel, mp2Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp2TextField = new JTextField(25);
addComponent(panel, mp2TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp3Label = new JLabel("MP3");
addComponent(panel, mp3Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp3TextField = new JTextField(25);
addComponent(panel, mp3TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp4Label = new JLabel("MP4");
addComponent(panel, mp4Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp4TextField = new JTextField(25);
addComponent(panel, mp4TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JLabel mp5Label = new JLabel("MP5");
addComponent(panel, mp5Label, 0, gridy, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
JTextField mp5TextField = new JTextField(25);
addComponent(panel, mp5TextField, 1, gridy++, 1, 1, normalInsets,
GridBagConstraints.LINE_START, GridBagConstraints.HORIZONTAL);
return panel;
}
private JPanel createEmailPanel() {
JPanel panel = new JPanel();
JButton submitButton = new JButton("Send to my email");
panel.add(submitButton);
return panel;
}
private void addComponent(Container container, Component component,
int gridx, int gridy, int gridwidth, int gridheight, Insets insets,
int anchor, int fill) {
GridBagConstraints gbc = new GridBagConstraints(gridx, gridy,
gridwidth, gridheight, 0.0D, 0.0D, anchor, fill, insets, 0, 0);
container.add(component, gbc);
}
public class Student {
private final int semester;
private final String id;
private final String name;
private final String jurusan;
public Student(String id, String name, String jurusan, int semester) {
this.id = id;
this.name = name;
this.jurusan = jurusan;
this.semester = semester;
}
public int getSemester() {
return semester;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getJurusan() {
return jurusan;
}
}
}
Hi I am unable to add panels separately to the components.Can you help me with the right code please.
import javax.swing.*;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.*;
public class Example3 extends JPanel
{
GridBagConstraints constraints = new GridBagConstraints();
public Example3()
{
setLayout(new GridBagLayout());
constraints.weightx = 1.0;
constraints.weighty = 1.0;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.insets=new Insets(5,5,5,5);
int x, y;
// Iwant to add panel to this section to the left side//
constraints.gridheight = 1;
addGB(new JLabel("label1"), x = 0, y = 0);
addGB(new JLabel("label2"), x = 0, y = 1);
addGB(new JLabel("label3"), x = 0, y = 2);
addGB(new JLabel("label4"), x = 0, y = 3);
addGB(new JLabel("label5"), x = 0, y = 4);
//i want another panel to add to this section to the bottom//
constraints.gridwidth=2;
addGB(new JTextField("txt1"), x=1, y=0);
addGB(new JButton("btn1"), x=1, y=1);
addGB(new JRadioButton("no"), x=1, y=2);
addGB(new JRadioButton("no"), x=1, y=2);
addGB(new JComboBox(), x=1, y=3);
addGB(new JTextField("txt3"), x=1, y=4);
addGB(new JButton("OK"), x=1, y=5);
//I want to add panels to this section in the center//
addGB(new JCheckBox("chk1"), x=3, y=0);
addGB(new JCheckBox("chk2"), x=3, y=1);
addGB(new JTextArea("txtar1"), x=3, y=2);
addGB(new JRadioButton("rbtn2"), x=3, y=3);
addGB(new JComboBox(), x=3, y=4);
addGB(new JButton("CANCEL"), x=3, y=5);
//I want to add panel to this section to right side//
addGB(new JCheckBox("chk3"), x=5, y=0);
addGB(new JCheckBox("chk4"), x=7, y=0);
}
void addGB(Component component, int x, int y)
{
constraints.gridx = x;
constraints.gridy = y;
add(component, constraints);
}
public static void main(String[] args)
{
JFrame frame = new JFrame("Welcome to Example3");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.setLocation(200, 200);
frame.setContentPane(new Example3());
frame.setVisible(true);
}
}
I want to add panels to labels separately and checkboxes separately using gridbag layout,JPanel.Can anyone suggest me with the right code please.
If you wont just to add JPanel you can add this code in your main
JFrame frame = new JFrame("Welcome to Example3");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
.....
//you miss those line
JPanel p = new JPanel();
frame.getContentPane().add(p);
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
public class PizzaGridBagLayout extends JFrame {
public static void main(String[] args) {
new PizzaGridBagLayout();
}
JTextField name = new JTextField(10), phone = new JTextField(10);JComboBox address = new JComboBox(new String[]{"ComboBox 1","hi","hello"});
JComboBox address1 = new JComboBox(new String[]{"ComboBox 2","hi","hello"});
JButton labels=new JButton("labels");
JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
JLabel label3 = new JLabel("Label3");
JLabel label4 = new JLabel("Label4");
JLabel label5 = new JLabel("Label5");
JRadioButton yes = new JRadioButton("yes"),
no = new JRadioButton("no");
JCheckBox box1 = new JCheckBox("box1"), box2 = new JCheckBox("box2"),
box3 = new JCheckBox("box3");
JButton okButton = new JButton("OK"), closeButton = new JButton("Close");
public PizzaGridBagLayout() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
//addItem(panel1, new JLabel(""), 0, 0, 1, 1, GridBagConstraints.CENTER);
// addItem(panel1, new JLabel(""), 1, 1, 1, 1, GridBagConstraints.CENTER);
// addItem(panel1, new JLabel(""), 1, 2, 1, 1, GridBagConstraints.CENTER);
addItem(panel1, name, 1, 2, 1, 0, GridBagConstraints.CENTER);
addItem(panel1, phone, 1, 2, 1, 1, GridBagConstraints.CENTER);
addItem(panel1, address, 1, 4, 1, 0, GridBagConstraints.CENTER);
addItem(panel1, address1, 1, 6, 1, 0, GridBagConstraints.CENTER);
Box sizeBox = Box.createVerticalBox();
//ButtonGroup sizeGroup = new ButtonGroup();
//sizeGroup.add(label1);
//sizeGroup.add(label2);
//sizeGroup.add(label3);
//sizeGroup.add(label4);
//sizeGroup.add(label5);
sizeBox.add(label1);
sizeBox.add(label2);
sizeBox.add(label3);
sizeBox.add(label4);
sizeBox.add(label5);
sizeBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, sizeBox, 0, 3, 1, 1, GridBagConstraints.NORTH);
addItem(panel1, label1, 0, 3, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label2, 0, 4, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label3, 0, 5, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label4, 0, 6, 1, 1,GridBagConstraints.NORTH);
addItem(panel1, label5, 0, 7, 1, 1,GridBagConstraints.NORTH);
/*Box sizeBox1 = Box.createVerticalBox();
ButtonGroup sizeGroup1 = new ButtonGroup();
sizeBox1.add(labels);
addItem(panel1, sizeBox1, 0, 1, 1, 0, GridBagConstraints.NORTH);*/
Box styleBox = Box.createVerticalBox();
// ButtonGroup styleGroup = new ButtonGroup();
// styleGroup.add(yes);
// styleGroup.add(no);
styleBox.add(yes);
styleBox.add(no);
styleBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, styleBox, 1, 3, 1, 1, GridBagConstraints.NORTH);
Box topBox = Box.createVerticalBox();
ButtonGroup topGroup = new ButtonGroup();
//topGroup.add(box1);
//topGroup.add(box2);
//topGroup.add(box3);
topBox.add(box1);
topBox.add(box2);
//topBox.add(box3);
topBox.setBorder(BorderFactory.createTitledBorder(""));
addItem(panel1, topBox, 2, 3, 1, 1, GridBagConstraints.NORTH);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(okButton);
addItem(panel1, buttonBox, 1, 6, 1, 1, GridBagConstraints.NORTH);
buttonBox.add(Box.createHorizontalStrut(20));
buttonBox.add(closeButton);
addItem(panel1, buttonBox, 2, 7, 1, 1, GridBagConstraints.NORTH);
this.add(panel1);
this.pack();
this.setVisible(true);
}
private void addItem(JPanel p, JComponent c, int x, int y, int width, int height, int align) {
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(2, 2, 2, 2);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
}