GUI pack and setVisible error - java

Im writing this for fun, this is not homework so please help me all you can. I am trying to make a "dice" that spits out various ski tricks that you can do and i cannot get my gui to come up or work.
public SkiDice20(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());
addItem(panel1, new JLabel("Name: "), 0, 0, 1, 1, GridBagConstraints.EAST);
addItem(panel1, newName, 1, 0, 2, 1, GridBagConstraints.WEST);
System.out.print(newName.getText());
Box slayBox = Box.createVerticalBox();
slayGroup.add(jump);
slayGroup.add(rail);
slayGroup.add(slope);
slayBox.add(jump);
slayBox.add(rail);
slayBox.add(slope);
slayBox.setBorder(BorderFactory.createTitledBorder("What are you Slaying?"));
addItem(panel1, slayBox, 0, 3, 1, 1, GridBagConstraints.NORTH);
Box skillBox = Box.createVerticalBox();
skillGroup.add(gaper);
skillGroup.add(nser);
skillGroup.add(am);
skillGroup.add(pro);
skillBox.add(gaper);
skillBox.add(nser);
skillBox.add(am);
skillBox.add(pro);
skillBox.setBorder(BorderFactory.
createTitledBorder("Skill?"));
addItem(panel1, skillBox, 1, 3, 1, 1, GridBagConstraints.NORTH);
Box buttonBox = Box.createHorizontalBox();
buttonBox.add(okButton);
buttonBox.add(Box.createHorizontalStrut(20));
buttonBox.add(completeButton);
addItem(panel1, buttonBox, 2, 4, 1, 1, GridBagConstraints.NORTH);
this.add(panel1);
this.pack();
this.setVisible(true);
And this is my main method.
public static void main(String[] args) {
String input = JOptionPane.showInputDialog ( "Number of people Skiing?" );
numberOfPeople = Integer.parseInt(input);
new SkiDice20();
checkSelection();
for (int i = 0; i < numberOfPeople; i++){
}
}
I am getting an error on these three lines and nothing else
this.add(panel1);
this.pack();
this.setVisible(true);
I know the cooardinates are screwed up right now, i took the code from an old project that i did but i forgot how i got this to work. Thank you for any help it is greatly appreciated

Needed to extend SkiDice20. After that it worked.

Related

setting componenets by using GridBagLayout

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.

Java help: JLabel's

I created this program that displays 2 photos and some facts (JLabel) about myself. However, the facts about myself are to the right of the pages. I would like the facts (JLabels) to be right under the pictures stacked, like a title and bullet points under the title, any help?
Ignore the import for sound. Eventually, I want the program to play a tune.
import java.awt.*;
import sun.audio.*;
import javax.swing.*;
public class AudioandImage extends JFrame {
public ImageIcon image1;
public JLabel label1;
public ImageIcon image2;
public JLabel label2;
public JLabel name;
public JLabel facts;
public JLabel born;
public JLabel es;
public JLabel sport;
public JLabel lastly;
AudioandImage() {
setLayout (new FlowLayout());
image1 = new ImageIcon(getClass().getResource("losangeles.jpg"));
label1 = new JLabel(image1);
add(label1);
image2 = new ImageIcon(getClass().getResource("elsalvador.jpg"));
label2 = new JLabel(image2);
add(label2);
name = new JLabel("My name is Erik Landaverde");
add(name);
facts = new JLabel("Some facts about myself:");
add(facts);
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born);
es = new JLabel("Have a Salvadorean background");
add(es);
sport = new JLabel("My favorite sport is soccer");
add(sport);
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly);
}
public static void main(String[] args) {
AudioandImage gui = new AudioandImage();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}
}
The desired result can be accomplished by assigning a different layout to your JFrame to FlowLayout() BorderLayout for example,
setLayout (new BorderLayout()); // asign layout to JFrame
add(label1,BorderLayout.PAGE_START); //Add JLabel 1 to Jframe
add(label2,BorderLayout.CENTER); //Add JLabel 2 to Jframe
name = new JLabel("<html><ul>My name is : Erik Landaverde "
+ "<li/>Some facts about myself: </li> "
+ "<li/>I was born and raised in South Central Los Angeles</li>"
+ "<li/>Have a Salvadorean background</li>"
+ "<li/>My favorite sport is soccer</li>"
+ "<li/>Lastly... I am a programmer!</li></ul></html>", SwingConstants.CENTER);
add(name,BorderLayout.PAGE_END); //Add JLabel 3 to Jframe
for the label in March added it into one because only contained what I
format strings with <html> </html> and line with <ul><li>content</li></ul>
Flow layout is not suited for the way you want to display the labels. See https://docs.oracle.com/javase/tutorial/uiswing/layout/flow.html for tutorial on flow layout.
You can also find tutorial to BorderLayout from above link. You could use this layout here. Create a JPanel with your labels using GridLayout with 1 column. Then place it in CENTER or SOUTH of the JFrame using BroderLayout.
Another approach could be to write your text as a single HTML and set it in JTextPane etc.
Use Below code for GridBagLayout
Test() {
setLayout(new GridBagLayout());
image1 = new ImageIcon(getClass().getClassLoader().getResource("image.jpg"));
label1 = new JLabel(image1);
add(label1, new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
name = new JLabel("My name is Erik Landaverde");
add(name, new GridBagConstraints(0, 2, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
facts = new JLabel("Some facts about myself:");
add(facts, new GridBagConstraints(0, 3, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
born = new JLabel("I was born and raised in South Central Los Angeles");
add(born, new GridBagConstraints(0, 4, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
es = new JLabel("Have a Salvadorean background");
add(es, new GridBagConstraints(0, 5, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
sport = new JLabel("My favorite sport is soccer");
add(sport, new GridBagConstraints(0, 6, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
lastly = new JLabel("Lastly... I am a programmer!");
add(lastly, new GridBagConstraints(0, 7, 1, 1, 1.0, 1.0, GridBagConstraints.NORTHEAST, GridBagConstraints.BOTH,
new Insets(0, 0, 0, 0), 0, 0));
}
public static void main(String[] args) {
Test gui = new Test();
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setVisible(true);
gui.pack();
gui.setTitle("A Little About Myself");
}

I want to add separate panels (using JPanel) in my code using gridbag layout .Can anyone one suggest me with the right code.Thanks in advance

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);
}
}

GridBagLayout format error. JTextFields in wrong positions

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:

GridBagLayout: alignment and width when gridwidth is > 1

In this JFrame with a GridBagLayout with 4 columns, the brown line should be the limit between columns 1 and 2, and OK and Cancel buttons should be on each side of this limit:
The problems:
OK + Cancel set is not centered with other buttons.
Left and right JTextArea don't have the same width.
Column 1 seems to have a zero width when I was expecting columns 1 and 2 to be equal.
The code used:
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class GblSO extends JFrame {
// Instance variables
GridBagConstraints gbc = new GridBagConstraints();
public GblSO() {
// Set frame
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
// Text areas
JTextArea left = new JTextArea("Left!");
JTextArea right = new JTextArea("Right!");
setConstraints(1, 1, GridBagConstraints.BOTH, null);
addToFrame(left, 0, 1, 1, 5, GridBagConstraints.CENTER);
addToFrame(right, 3, 1, 1, 5, GridBagConstraints.CENTER);
// Transfer buttons
JButton addBtn = new JButton(">");
JButton rmvBtn = new JButton("<");
setConstraints(0, 0, GridBagConstraints.NONE, new Insets(3, 5, 3, 5));
addToFrame(addBtn, 1, 1, 2, 1, GridBagConstraints.CENTER);
addToFrame(rmvBtn, 1, 3, 2, 1, GridBagConstraints.CENTER);
// OK / Cancel buttons
JButton okBtn = new JButton("OK");
JButton canBtn = new JButton("Cancel");
setConstraints(0, 0, GridBagConstraints.NONE, new Insets(15, 4, 15, 4));
addToFrame(okBtn, 0, 6, 2, 1, GridBagConstraints.EAST);
addToFrame(canBtn, 2, 6, 2, 1, GridBagConstraints.WEST);
// Show
pack();
setVisible(true);
}
private void setConstraints(double weightx, double weighty, int fill, Insets insets) {
gbc.weightx = weightx; // how much cell resizes
gbc.weighty = weighty; // "
gbc.fill = fill; // how component fills cell
gbc.insets = (insets == null ? new Insets(0, 0, 0, 0) : insets);
}
private void addToFrame(Component comp,
int gridx, int gridy, int gridwidth, int gridheight, int anchor) {
gbc.gridx = gridx;
gbc.gridy = gridy;
gbc.gridwidth = gridwidth;
gbc.gridheight = gridheight;
gbc.anchor = anchor;
add(comp, gbc);
}
public static void main(String[] args) {
new GblSO();
}
}
For a test only: If I add the > and < buttons to the JFrame respectively in column 1 and 2, and don't span multiple columns, columns 1 and 2 are forced to have the same width and the bottom buttons set is now centered.
Code changed:
addToFrame(addBtn, 1, 1, 1, 1, GridBagConstraints.CENTER);
addToFrame(rmvBtn, 2, 3, 1, 1, GridBagConstraints.CENTER);
Result:
The two JTextArea have still a different width :-(, and obviously > and < are not going to be aligned!
How can I solve this problem so that buttons are centered, and the two JTextArea have the same width? Thanks by advance for your help.
(this code is inspired by this tutorial)
That is because you don't have any components added on each column, which is somehow needed for GridBagLayout to work as one would expect.
A few remarks now:
Did you noticed in the tutorial you linked to, the OK and Cancel buttons are aligned with the JTextArea, not the overall upper components?
When working with GridBagLayout it is better to instanciate a new GridBagConstraint for each component you're adding. It prevents you from forgetting to reset an attribute somewhere, which is difficult to troubleshoot.
Then, if you want your OK and Cancel buttons to be center-aligned with your upper components, the easiest would be to create two JPanel: one with the upper components, the other one with your buttons. You can still use GridBagLayout for the upper panel and the default one (FlowLayout) for the buttons. You would put them into a BorderLayout position CENTER and SOUTH and you'd be good to go. Note that the panels would be center-aligned, not the space between the OK / Cancel buttons and the < / > buttons.
Back to the solution to your problem: you have to add "empty" components (Container, JPanel, emtpy JLabel, ...) on the first (or last) line with weightx set to 1.0 so the cells are actually filled in X direction, and weighty set to 0.0 so they are not visible in Y direction (and vice-versa if you want to use gridheight instead of gridwidth).
...
setLayout(new GridBagLayout());
setConstraints(1, 0, GridBagConstraints.BOTH, null);
addToFrame(new Container(), 0, 0, 1, 1, GridBagConstraints.CENTER);
addToFrame(new Container(), 1, 0, 1, 1, GridBagConstraints.CENTER);
addToFrame(new Container(), 2, 0, 1, 1, GridBagConstraints.CENTER);
addToFrame(new Container(), 3, 0, 1, 1, GridBagConstraints.CENTER);
// Text areas
...
That way the cells will exist and you'll get the expected result.

Categories