GUI has random spacing between it - java

I started working on this GUI recently for my CS class and for some reason the output I get is completely inconsistent and makes no sense whatsoever.
Here's an example of what I mean:
In my code I have certain constraints for my buttons which utilize the GridBagLayout.
GridBagConstraints countrytextRestraints = new GridBagConstraints();
countrytextRestraints.gridx = 1;
countrytextRestraints.gridy = 30;
GridBagConstraints country1restraints = new GridBagConstraints();
country1restraints.gridx = 2;
country1restraints.gridy = 30;
GridBagConstraints country2restraints = new GridBagConstraints();
country2restraints.gridx = 3;
country2restraints.gridy = 30;
GridBagConstraints country3restraints = new GridBagConstraints();
country3restraints.gridx = 4;
country3restraints.gridy = 30;
As you can see, the gridX values for each of the buttons are never more than 1 pixel apart but for some reason my output ends up looking like this
with a far more disproportionate amount of space than the other elements. This happens at multiple points in the code. What's going on?
Here's all my code for additional help
package Starting;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class View extends JPanel implements ActionListener {
View(Container pane) {
pane.setLayout(new GridBagLayout());
ImageIcon myImage = new ImageIcon("Elf.jpg");
Image resizedElf = myImage.getImage();
resizedElf = resizedElf.getScaledInstance(80, 60, Image.SCALE_DEFAULT);
myImage = new ImageIcon(resizedElf);
JLabel myImageLabel = new JLabel();
myImageLabel.setIcon(myImage);
GridBagConstraints imageConstraints = new GridBagConstraints();
//X is cols
//Y is row
imageConstraints.gridx = 0;
imageConstraints.gridy = 0;
imageConstraints.gridheight = 1;
imageConstraints.gridwidth = 1;
pane.add(myImageLabel, imageConstraints);
JList theGames = new JList();
JLabel Company = new JLabel("Company");
// The Country buttons
JLabel Country = new JLabel("Country:");
ButtonGroup countryofOrigin = new ButtonGroup();
JRadioButton country1 = new JRadioButton("Japan");
JRadioButton country2 = new JRadioButton("U.S");
JRadioButton country3 = new JRadioButton("Canada");
GridBagConstraints countrytextRestraints = new GridBagConstraints();
countrytextRestraints.gridx = 1;
countrytextRestraints.gridy = 30;
GridBagConstraints country1restraints = new GridBagConstraints();
country1restraints.gridx = 2;
country1restraints.gridy = 30;
GridBagConstraints country2restraints = new GridBagConstraints();
country2restraints.gridx = 3;
country2restraints.gridy = 30;
GridBagConstraints country3restraints = new GridBagConstraints();
country3restraints.gridx = 4;
country3restraints.gridy = 30;
//Model is all of the data
//Methods in controller called through actionlistener
//View is correct
country1.addActionListener(e -> {});
country2.addActionListener(e -> {});
country3.addActionListener(e -> {});
countryofOrigin.add(country1);
countryofOrigin.add(country2);
countryofOrigin.add(country3);
pane.add(country1, country1restraints);
pane.add(country2, country2restraints);
pane.add(country3, country3restraints);
pane.add(Country, countrytextRestraints);
//Genre buttons
JLabel Genre = new JLabel("Genre");
ButtonGroup thegenres = new ButtonGroup();
JRadioButton action = new JRadioButton("Action");
action.addActionListener(event -> { });
JRadioButton RPG = new JRadioButton("RPG");
RPG.addActionListener(event -> { });
JRadioButton Puzzle = new JRadioButton("Puzzle");
Puzzle.addActionListener(event -> { });
thegenres.add(action);
thegenres.add(RPG);
thegenres.add(Puzzle);
GridBagConstraints genreTextconstraints = new GridBagConstraints();
genreTextconstraints.gridx = 1;
genreTextconstraints.gridy = 40;
GridBagConstraints actionRestraints = new GridBagConstraints();
actionRestraints.gridx = 2;
actionRestraints.gridy = 40;
GridBagConstraints RPGconstraints = new GridBagConstraints();
RPGconstraints.gridx = 3;
RPGconstraints.gridy = 40;
GridBagConstraints puzzleConstraints = new GridBagConstraints();
puzzleConstraints.gridx = 4;
puzzleConstraints.gridy = 40;
pane.add(action, actionRestraints);
pane.add(RPG, RPGconstraints);
pane.add(Puzzle, puzzleConstraints);
pane.add(Genre,genreTextconstraints);
JLabel PriceLabel = new JLabel("Price");
JTextField priceText = new JTextField("Enter price");
priceText.addActionListener(event -> { });
JLabel DescriptionLabel = new JLabel("Description");
JTextField Description = new JTextField("Describe the game here!");
JButton cancel = new JButton("cancel");
cancel.addActionListener(e -> { });
JButton save = new JButton("Save");
save.addActionListener(e -> { });
GridBagConstraints priceLabelConstraints = new GridBagConstraints();
priceLabelConstraints.gridx = 1;
priceLabelConstraints.gridy = 20;
GridBagConstraints priceTextConstraints = new GridBagConstraints();
priceTextConstraints.gridx = 2;
priceTextConstraints.gridy = 20;
GridBagConstraints DescriptionLabelConstraints = new GridBagConstraints();
DescriptionLabelConstraints.gridx = 29;
DescriptionLabelConstraints.gridy = 50;
GridBagConstraints DescriptionConstraints = new GridBagConstraints();
DescriptionConstraints.gridx = 30;
DescriptionConstraints.gridy = 50;
GridBagConstraints CancelConstraints = new GridBagConstraints();
CancelConstraints.gridx = 10;
CancelConstraints.gridy = 70;
GridBagConstraints saveConstraints = new GridBagConstraints();
saveConstraints.gridx = 11;
saveConstraints.gridy = 70;
pane.add(PriceLabel,priceLabelConstraints);
pane.add(priceText, priceTextConstraints);
pane.add(DescriptionLabel, DescriptionLabelConstraints);
pane.add(Description, DescriptionConstraints);
pane.add(cancel, CancelConstraints);
pane.add(save, saveConstraints);
JList listofGames = new JList();
listofGames.addListSelectionListener(e -> {});
GridBagConstraints listofGamesconstraints = new GridBagConstraints();
listofGamesconstraints.gridx = 60;
listofGamesconstraints.gridy = 60;
pane.add(listofGames, listofGamesconstraints);
}
#Override
public void actionPerformed(ActionEvent e) {
}
public static void main(String[] args) {
}
}
And
package Starting;
import javax.swing.*;
import java.awt.*;
public class Starter {
public static void main(String[] args) {
JFrame frame = new JFrame("Example Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(800,600));
mainPanel.setBackground(Color.white);
View theview = new View(frame.getContentPane());
theview.setPreferredSize(new Dimension(800,600));
theview.setLayout(new GridBagLayout());
mainPanel.add(theview);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setVisible(true);
}
}
Here's what I want it too look like for reference

As promised.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Hashtable;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerModel;
import javax.swing.WindowConstants;
public class Starters implements Runnable {
#Override // java.lang.Runnable
public void run() {
createAndShowGui();
}
private void createAndShowGui() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(createForm(), BorderLayout.CENTER);
frame.add(createButtonsPanel(), BorderLayout.PAGE_END);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.TRAILING));
JButton cancelButton = new JButton("Cancel");
buttonsPanel.add(cancelButton);
JButton saveButton = new JButton("Save");
buttonsPanel.add(saveButton);
return buttonsPanel;
}
private JPanel createCountriesPanel() {
JPanel countriesPanel = new JPanel();
ButtonGroup bg = new ButtonGroup();
JRadioButton northAmerica = new JRadioButton("North America");
JRadioButton japan = new JRadioButton("Japan");
JRadioButton canada = new JRadioButton("Canada");
bg.add(northAmerica);
bg.add(japan);
bg.add(canada);
countriesPanel.add(northAmerica);
countriesPanel.add(japan);
countriesPanel.add(canada);
return countriesPanel;
}
private JPanel createForm() {
JPanel form = new JPanel(new GridBagLayout());
form.setBorder(BorderFactory.createEmptyBorder(5, 0, 10, 15));
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
ImageIcon imgIco = new ImageIcon("path-to-your-image-file");
JLabel img = new JLabel(imgIco);
form.add(img, gbc);
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 1;
gbc.gridy = 1;
JLabel nameLabel = new JLabel("Name");
form.add(nameLabel, gbc);
gbc.gridx = 2;
form.add(createNameSpinner(), gbc);
gbc.gridx = 1;
gbc.gridy = 2;
JLabel companyLabel = new JLabel("Company");
form.add(companyLabel, gbc);
gbc.gridx = 2;
JTextField companyTextField = new JTextField(7);
form.add(companyTextField, gbc);
gbc.gridx = 1;
gbc.gridy = 3;
JLabel countryLabel = new JLabel("Country");
form.add(countryLabel, gbc);
gbc.gridx = 2;
form.add(createCountriesPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 4;
JLabel typeLabel = new JLabel("Type");
form.add(typeLabel, gbc);
gbc.gridx = 2;
form.add(createTypesPanel(), gbc);
gbc.gridx = 1;
gbc.gridy = 5;
JLabel lengthLabel = new JLabel("Game Length");
form.add(lengthLabel, gbc);
gbc.gridx = 2;
form.add(createSlider(), gbc);
gbc.gridx = 1;
gbc.gridy = 6;
JLabel priceLabel = new JLabel("Price");
form.add(priceLabel, gbc);
gbc.gridx = 2;
JTextField priceTextField = new JTextField(7);
form.add(priceTextField, gbc);
gbc.gridx = 1;
gbc.gridy = 7;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
JLabel descriptionLabel = new JLabel("Description");
form.add(descriptionLabel, gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.LINE_START;
JTextArea description = new JTextArea(5, 40);
description.setLineWrap(true);
description.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(description);
form.add(scrollPane, gbc);
return form;
}
private JSpinner createNameSpinner() {
SpinnerModel model = new SpinnerListModel(new String[]{"Reuben",
"Simeon",
"Levi",
"Judah",
"Dan",
"Naphtali",
"Gad",
"Asher",
"Issachar",
"Zebulun",
"Joseph",
"Benjamin"});
JSpinner nameSpinner = new JSpinner(model);
return nameSpinner;
}
private JSlider createSlider() {
JSlider slider = new JSlider(30, 100, 50);
Hashtable<Integer, JComponent> labels = new Hashtable<>(2);
labels.put(Integer.valueOf(30), new JLabel("30"));
labels.put(Integer.valueOf(100), new JLabel("100"));
slider.setLabelTable(labels);
slider.setPaintLabels(true);
return slider;
}
private JPanel createTypesPanel() {
JPanel typesPanel = new JPanel();
ButtonGroup bg = new ButtonGroup();
JRadioButton action = new JRadioButton("Action");
JRadioButton rpg = new JRadioButton("RPG");
JRadioButton puzzle = new JRadioButton("Puzzle");
bg.add(action);
bg.add(rpg);
bg.add(puzzle);
typesPanel.add(action);
typesPanel.add(rpg);
typesPanel.add(puzzle);
return typesPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Starters());
}
}

Related

Adding a JPanel to another JPanel

I want to add multiple JPanels to one JPanel. Then I want to take that JPanel and display it in a tab of a JTabbedPane. I attempted to do it a few times but eclipse won't let me run the program. It doesn't show any errors but the program always runs in debug mode for some reason. Is it something wrong with the code? (The code is a bit long sorry)
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.Serializable;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ScrollPaneConstants;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
public class GuiApp {
static class shelf implements Serializable {
// declare books and variables
static shelf[] book = new shelf[1000];
Boolean overdue;
Boolean checkedOut;
int bookNum;
String personName;
String dueDate;
int month;
int date;
int year;
String dateCheckedOut;
String bookName;
}
public static void main(String args[]) {
// set L&F
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
}
JFrame main = new JFrame();
JTabbedPane tabs = new JTabbedPane();
JPanel checkOutPanel = new JPanel(new GridBagLayout());
JPanel checkInPanel = new JPanel(new GridBagLayout());
JPanel checkedOutOverduePanel = new JPanel(new BorderLayout());
JPanel assignNamesPanel = new JPanel(new BorderLayout());
JPanel refreshSavePanel = new JPanel(new GridBagLayout());
//misc
Font f = new Font("Header", Font.BOLD, 24);
GridBagConstraints gbc = new GridBagConstraints();
//check out
JLabel checkOutLabel = new JLabel("CheckOut");
JLabel bookNumLabel = new JLabel("Book Number");
JLabel personNameLabel = new JLabel("Person Name");
final JTextField bookNumEntry = new JTextField(20);
final JTextField personNameEntry = new JTextField(20);
JButton checkOutButton = new JButton("Check out");
checkOutLabel.setFont(f);
gbc.gridx = 1;
checkOutPanel.add(checkOutLabel,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
checkOutPanel.add(bookNumLabel,gbc);
gbc.gridx = 1;
checkOutPanel.add(bookNumEntry,gbc);
gbc.gridx = 0;
gbc.gridy = 2;
checkOutPanel.add(personNameLabel,gbc);
gbc.gridx = 1;
checkOutPanel.add(personNameEntry,gbc);
gbc.gridx = 2;
checkOutPanel.add(checkOutPanel,gbc);
tabs.addTab("Check Out", checkOutPanel);
//check in
JLabel checkInLabel = new JLabel("Check In");
JLabel bookNumCheckInLabel = new JLabel("Book Number");
final JTextField bookNumCheckIn = new JTextField(20);
JButton checkInButton = new JButton("Check In");
checkInLabel.setFont(f);
gbc.gridx = 1;
gbc.gridy = 0;
checkInPanel.add(checkInLabel,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
checkInPanel.add(bookNumCheckInLabel,gbc);
gbc.gridx = 1;
checkInPanel.add(bookNumCheckIn,gbc);
gbc.gridy = 2;
checkInPanel.add(checkInButton,gbc);
tabs.addTab("Check In",checkInPanel);
//checked out overdue
JPanel co = new JPanel(new GridBagLayout());
JPanel co2 = new JPanel(new GridBagLayout());
JPanel co3 = new JPanel();
JLabel booksOutOverdueLabel = new JLabel("BOOKS OUT/OVERDUE");
JLabel checkedOutLabel = new JLabel("Checked out");
JLabel overdueLabel = new JLabel("Overdue");
booksOutOverdueLabel.setFont(f);
JTextArea checkedOutBooks = new JTextArea(50,53);
JTextArea overdueBooks = new JTextArea(50,48);
JScrollPane checkedOutTA = new JScrollPane(checkedOutBooks);
JScrollPane overdueTA = new JScrollPane(overdueBooks);
checkedOutTA.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
overdueTA.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
checkedOutBooks.setEditable(false);
overdueBooks.setEditable(false);
gbc.gridy = 0;
co.add(checkedOutLabel,gbc);
gbc.gridy = 1;
co.add(checkedOutTA,gbc);
gbc.gridy = 0;
co2.add(overdueLabel,gbc);
gbc.gridy = 1;
co2.add(overdueTA,gbc);
co3.add(booksOutOverdueLabel);
checkedOutOverduePanel.add(co3,BorderLayout.NORTH);
checkedOutOverduePanel.add(co,BorderLayout.WEST);
checkedOutOverduePanel.add(co2,BorderLayout.EAST);
tabs.addTab("Checked Out/Overdue",checkedOutOverduePanel);
//assign book names
JPanel an = new JPanel(new GridBagLayout());
JPanel an2 = new JPanel();
JLabel assignNamesLabel = new JLabel("Assign Book Names");
JLabel bookNumberLabel = new JLabel("Book Number");
JLabel nameOfBookLabel = new JLabel("Book Name");
final JTextField bookNumber = new JTextField(20);
final JTextField bookName = new JTextField(20);
JButton assignName = new JButton("Assign");
assignNamesLabel.setFont(f);
gbc.gridy = 0;
an.add(bookNumberLabel,gbc);
an.add(bookNumber,gbc);
gbc.gridy = 1;
an.add(nameOfBookLabel,gbc);
an.add(bookName,gbc);
gbc.gridy = 2;
gbc.gridx = 1;
an.add(assignName,gbc);
an2.add(assignNamesLabel);
assignNamesPanel.add(an2,BorderLayout.NORTH);
assignNamesPanel.add(an,BorderLayout.CENTER);
tabs.addTab("Assign Book Names",assignNamesPanel);
//refresh and save
JButton saveButton = new JButton("Save");
JButton refreshButton = new JButton("Refresh");
refreshSavePanel.add(saveButton);
refreshSavePanel.add(refreshButton);
tabs.addTab("Refresh/save",refreshSavePanel);
tabs.setTabPlacement(JTabbedPane.LEFT);
main.add(tabs);
main.setSize(1300,1100);
main.setVisible(true);
}
}
here is the problem you are adding panel to itself .adding container's parent to itself
checkOutPanel.add(checkOutPanel,gbc);//error
tabs.addTab("Check Out", checkOutPanel);
you should add component to container.but you are adding container to container .probably you are trying to add a button .
checkOutPanel.add(checkOutButton,gbc);
tabs.addTab("Check Out", checkOutPanel);

Java GUI: How do I have more than one button on a row using GridBagLayout

I'm fairly new to java and I'm having a problem trying to put more than one button on a row,
at the moment I'm adding both buttons to the panel, but I don't know how to separate their x locations, i.e. they are both being added directly on to of each other.
Do I need to create a new layout or can I find a solution using what I have at the moment?
public class Question1 {
public static void main (String[] args){
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame{
MyFrame(String title){
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init(){
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10,20,10,20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf,cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JButton b = new JButton("Submit");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
b = new JButton("Cancel");
gbLayout.setConstraints(b,cButton);
mainPanel.add(b);
this.pack();
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE) ;
this.setVisible(true);
}
Just increment the gridx value:
JButton b = new JButton("Submit");
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
b = new JButton("Cancel");
cButton.gridx++;
// gbLayout.setConstraints(b,cButton);
mainPanel.add(b, cButton);
Also you need to use the constraints created when adding your component to the grid bag layout using container.
e.g.,
import java.awt.*;
import javax.swing.*;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
private static final int GAP = 2;
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(GAP, GAP, GAP, GAP);
gbc.gridwidth = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
JTextField tf = new JTextField(20);
mainPanel.add(tf, gbc);
gbc.gridwidth = 1;
gbc.gridx = 0;
gbc.gridy = 1;
JButton b = new JButton("Submit");
mainPanel.add(b, gbc);
b = new JButton("Cancel");
gbc.gridx++;
mainPanel.add(b, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
Try the following code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Question1 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Simple Submit Cancel Form");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints cText = new GridBagConstraints();
private GridBagConstraints cButton = new GridBagConstraints();
private GridBagLayout gbLayout = new GridBagLayout();
void init() {
mainPanel = new JPanel();
mainPanel.setLayout(gbLayout);
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
this.setContentPane(mainPanel);
cText.anchor = GridBagConstraints.WEST;
cText.weightx = 0.0;
cText.gridx = 0;
cText.gridy = 0;
JTextField tf = new JTextField(20);
gbLayout.setConstraints(tf, cText);
mainPanel.add(tf);
cButton.gridwidth = 4;
cButton.weightx = 0.0;
cButton.gridx = 0;
cButton.gridy = 1;
JPanel demoPanel = new JPanel();
JButton b = new JButton("Submit");
gbLayout.setConstraints(demoPanel, cButton);
demoPanel.add(b);
b = new JButton("Cancel");
// gbLayout.setConstraints(b,cButton);
demoPanel.add(b);
mainPanel.add(demoPanel);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
I have just put the two buttons inside a JPanel and put the JPanel inside the GridBagLayout Panel !

How to add JSeparator between two JLabels in GridBagLayout

I want to have a JSeparator between each JLabel in a GridBagLayout. Currently it looks like this:
And now I want to add a JSeparator after each TESTSTEP Label in between the icon and the JLabel. The following constraint are only for the JLabel and the icon. What do I have to add to get a JSeparator all over the complete vertical line?
GridBagConstraints lastConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
lastConstraints.fill = GridBagConstraints.NONE;
lastConstraints.anchor = GridBagConstraints.EAST;
lastConstraints.weightx = 0.0;
lastConstraints.gridwidth = GridBagConstraints.REMAINDER;
lastConstraints.insets = new Insets(8, 8, 8, 8);
labelConstraints = (GridBagConstraints) lastConstraints.clone();
labelConstraints.weightx = 0.0;
labelConstraints.fill = GridBagConstraints.NONE;
labelConstraints.anchor = GridBagConstraints.WEST;
labelConstraints.gridwidth = 1;
Use:
fill = HORIZONTAL;
weightx = 1.0;
gridwidth = REMAINDER;
Small example:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
public class TestJSeparator {
public TestJSeparator() {
JFrame frame = new JFrame(TestJSeparator.class.getSimpleName());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel bigPanel = new JPanel(new GridBagLayout());
GridBagConstraints lastConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
GridBagConstraints separatorConstraint = new GridBagConstraints();
lastConstraints.fill = GridBagConstraints.NONE;
lastConstraints.anchor = GridBagConstraints.EAST;
lastConstraints.weightx = 0.0;
lastConstraints.gridwidth = GridBagConstraints.REMAINDER;
lastConstraints.insets = new Insets(8, 8, 8, 8);
labelConstraints = (GridBagConstraints) lastConstraints.clone();
labelConstraints.weightx = 0.0;
labelConstraints.fill = GridBagConstraints.NONE;
labelConstraints.anchor = GridBagConstraints.WEST;
labelConstraints.gridwidth = 1;
separatorConstraint.weightx = 1.0;
separatorConstraint.fill = GridBagConstraints.HORIZONTAL;
separatorConstraint.gridwidth = GridBagConstraints.REMAINDER;
JLabel label1 = new JLabel("1. TESTSTEP 0 TEST 0 DE");
JLabel result1 = new JLabel(UIManager.getIcon("OptionPane.informationIcon"));
JLabel label2 = new JLabel("2. TESTSTEP 0 TEST 1 DE");
JLabel result2 = new JLabel(UIManager.getIcon("OptionPane.errorIcon"));
bigPanel.add(label1, labelConstraints);
bigPanel.add(result1, lastConstraints);
bigPanel.add(new JSeparator(JSeparator.HORIZONTAL), separatorConstraint);
bigPanel.add(label2, labelConstraints);
bigPanel.add(result2, lastConstraints);
bigPanel.add(new JSeparator(JSeparator.HORIZONTAL), separatorConstraint);
frame.add(bigPanel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
TestJSeparator gui = new TestJSeparator();
}
});
}
}

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

I want to add a JLabel and Text box dynamically by clicking add button

When i create the text and label box dynamically it should sit in the format of "Textbox: Labelbox" then when i click on add button again the same pattern should repeat on next line and so on... Which layout should i use and how ?
This is the code i used
if(field_name.getText().equals("")){
error.setForeground(Color.red);
error.setText("Enter the Field name first");
} else {
JLabel l = new JLabel(field_name.getText(), JLabel.RIGHT);
JTextField textField = new JTextField();
Dimension dim = new Dimension(20,30);
textField.setPreferredSize(dim);
field_layer.add(l);
field_layer.add(textField);
SpringUtilities.makeCompactGrid(field_layer,
numPairs, 2, //rows, cols
6, 6, //initX, initY
6, 6); //xPad, yPad
numPairs++;
field_layer.invalidate();
this.pack();
}
One option is GridBagLayout. In order to use this layout properly, you'll need to understand GridBagConstraints. Here's a tutorial to help you get started.
Here's a quick example:
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MyExample
{
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
public static void main(String[] args)
{
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setPreferredSize(new Dimension(300, 300));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 0;
frame.add(addButton, frameConstraints);
// Construct panel
panel.setPreferredSize(new Dimension(200, 200));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 1;
frame.add(panel, frameConstraints);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Clear panel
panel.removeAll();
// Create label and text field
listOfTextFields.add(new JTextField());
listOfLabels.add(new JLabel("Label " + indexer));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for(int i = 0; i < indexer; i++)
{
// Text field constraints
textFieldConstraints.gridx = 0;
textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 1;
labelConstraints.gridy = i;
// Add them to panel
panel.add(listOfTextFields.get(i), textFieldConstraints);
panel.add(listOfLabels.get(i), labelConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
}
}
}
Note: don't limit yourself to this particular layout manager. That is, you should explore other Layout Managers too.
I have made slight change to the above code.....
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class MyExample
{
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
public static void main(String[] args)
{
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("My Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
addButton.addActionListener(new ButtonListener());
// Add button to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 0;
frame.add(addButton, frameConstraints);
// Construct panel
panel.setPreferredSize(new Dimension(600, 600));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frameConstraints.weighty = 1;
frame.add(panel, frameConstraints);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener
{
#Override
public void actionPerformed(ActionEvent arg0)
{
// Clear panel
panel.removeAll();
// Create label and text field
JTextField jTextField = new JTextField();
jTextField.setSize(100, 200);
listOfTextFields.add(jTextField);
listOfLabels.add(new JLabel("Label " + indexer));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
// Add labels and text fields
for(int i = 0; i < indexer; i++)
{
// Text field constraints
textFieldConstraints.gridx = 1;
textFieldConstraints.fill = GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.insets = new Insets(10, 10, 10, 10);
textFieldConstraints.gridy = i;
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
panel.add(listOfTextFields.get(i), textFieldConstraints);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
panel.updateUI();
}
}
}
I would recommend a GridBagLayout. You can use:
JPanel pan = new JPanel(); // For Swing
//or Panel pan = new Panel(); for AWT
pan.setLayout(new GridBagLayout());
GridBagConstraints textC = new GridBagConstraints();
textC.gridx = 0;
GridBagConstraints labelC= new GridBagConstraints();
labelC.gridx = 1;
// For Every (J)TextField
pan.add(text,textC);
// For Every (J)Label
label.add(label,labelC);
i modify some code and
see this
package formbuilder;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;
public class CreateFormFields {
// Field members
static JPanel panel = new JPanel();
static Integer indexer = 1;
static List<JLabel> listOfLabels = new ArrayList<JLabel>();
static List<JTextField> listOfTextFields = new ArrayList<JTextField>();
static List<JTextField> listDataType = new ArrayList<JTextField>();
static List<JTextField> listRange = new ArrayList<JTextField>();
static List<JTextField> listLable = new ArrayList<JTextField>();
public static void main(String[] args) {
// Construct frame
JFrame frame = new JFrame();
frame.setLayout(new GridBagLayout());
frame.setPreferredSize(new Dimension(990, 990));
frame.setTitle("Form Creator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Frame constraints
GridBagConstraints frameConstraints = new GridBagConstraints();
// Construct button
JButton addButton = new JButton("Add");
JButton createButton = new JButton("Create Form");
addButton.addActionListener(new ButtonListener());
createButton.addActionListener(new CreateForm());
// Add button to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 0;
frame.add(addButton, frameConstraints);
frameConstraints.gridx = 0;
frameConstraints.gridy = 1;
frame.add(createButton, frameConstraints);
// Construct panel
panel.setPreferredSize(new Dimension(900, 900));
panel.setLayout(new GridBagLayout());
panel.setBorder(LineBorder.createBlackLineBorder());
// Add panel to frame
frameConstraints.gridx = 0;
frameConstraints.gridy = 2;
frameConstraints.weighty = 1;
frame.add(panel, frameConstraints);
// Pack frame
frame.pack();
// Make frame visible
frame.setVisible(true);
}
static class ButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// Clear panel
panel.removeAll();
// Create label and text field
JTextField jTextField = new JTextField();
jTextField.setSize(5, 20);
JTextField jTextField2 = new JTextField();
jTextField2.setSize(6, 20);
JTextField jTextField3 = new JTextField();
jTextField3.setSize(7, 20);
JTextField jTextField4 = new JTextField();
jTextField4.setSize(8, 20);
listOfTextFields.add(jTextField);
listDataType.add(jTextField2);
listRange.add(jTextField3);
listLable.add(jTextField4);
listOfLabels.add(new JLabel("LableName | FieldName | DataType | Range "));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
GridBagConstraints gridlistDataType = new GridBagConstraints();
GridBagConstraints gridlistRange = new GridBagConstraints();
GridBagConstraints gridlistLable = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Text field constraints
textFieldConstraints.gridx = 1;
textFieldConstraints.fill = 1;//GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.insets = new Insets(10, 10, 10, 10);
textFieldConstraints.gridy = i;
gridlistDataType.gridx = 2;
gridlistDataType.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistDataType.weightx = 0.5;
gridlistDataType.insets = new Insets(10, 10, 10, 10);
gridlistDataType.gridy = i;
gridlistRange.gridx = 3;
gridlistRange.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistRange.weightx = 0.5;
gridlistRange.insets = new Insets(10, 10, 10, 10);
gridlistRange.gridy = i;
gridlistLable.gridx = 4;
gridlistLable.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistLable.weightx = 0.5;
gridlistLable.insets = new Insets(10, 10, 10, 10);
gridlistLable.gridy = i;
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
panel.add(listOfTextFields.get(i), textFieldConstraints);
panel.add(listDataType.get(i), gridlistDataType);
panel.add(listRange.get(i), gridlistRange);
panel.add(listLable.get(i), gridlistLable);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
panel.updateUI();
}
}
static class CreateForm implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
// Clear panel
panel.removeAll();
// Create label and text field
JTextField jTextField = new JTextField();
jTextField.setSize(5, 20);
JTextField jTextField2 = new JTextField();
jTextField2.setSize(6, 20);
JTextField jTextField3 = new JTextField();
jTextField3.setSize(7, 20);
JTextField jTextField4 = new JTextField();
jTextField4.setSize(8, 20);
listOfTextFields.add(jTextField);
listDataType.add(jTextField2);
listRange.add(jTextField3);
listLable.add(jTextField4);
listOfLabels.add(new JLabel("LableName | FieldName | DataType | Range "));
// Create constraints
GridBagConstraints textFieldConstraints = new GridBagConstraints();
GridBagConstraints labelConstraints = new GridBagConstraints();
GridBagConstraints gridlistDataType = new GridBagConstraints();
GridBagConstraints gridlistRange = new GridBagConstraints();
GridBagConstraints gridlistLable = new GridBagConstraints();
// Add labels and text fields
for (int i = 0; i < indexer; i++) {
// Label constraints
labelConstraints.gridx = 0;
labelConstraints.gridy = i;
labelConstraints.insets = new Insets(10, 10, 10, 10);
// Text field constraints
textFieldConstraints.gridx = 1;
textFieldConstraints.fill = 1;//GridBagConstraints.HORIZONTAL;
textFieldConstraints.weightx = 0.5;
textFieldConstraints.insets = new Insets(10, 10, 10, 10);
textFieldConstraints.gridy = i;
gridlistDataType.gridx = 2;
gridlistDataType.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistDataType.weightx = 0.5;
gridlistDataType.insets = new Insets(10, 10, 10, 10);
gridlistDataType.gridy = i;
gridlistRange.gridx = 3;
gridlistRange.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistRange.weightx = 0.5;
gridlistRange.insets = new Insets(10, 10, 10, 10);
gridlistRange.gridy = i;
gridlistLable.gridx = 4;
gridlistLable.fill = 1;//GridBagConstraints.HORIZONTAL;
gridlistLable.weightx = 0.5;
gridlistLable.insets = new Insets(10, 10, 10, 10);
gridlistLable.gridy = i;
// Add them to panel
panel.add(listOfLabels.get(i), labelConstraints);
panel.add(listOfTextFields.get(i), textFieldConstraints);
panel.add(listDataType.get(i), gridlistDataType);
panel.add(listRange.get(i), gridlistRange);
panel.add(listLable.get(i), gridlistLable);
}
// Align components top-to-bottom
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = indexer;
c.weighty = 1;
panel.add(new JLabel(), c);
// Increment indexer
indexer++;
panel.updateUI();
}
}
}

Categories

Resources