Dynamicly adding JPanels to a JFrame - java

This is my first question inhere, so please bear with me :)
Im working on a dynamic part of a GUI, and for some reason its teasing me.
The class is opened in a new window after login.
What I want, is for a new JPanel to be built and added to 'container' every time the "add player" button is clicked. It is supposed to put them below eachother, yet all it does is to add one button on the first click, and then the rest of the clicks afterwards does nothing.
Any help is appreciated :)
package Gui;
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 javax.swing.JButton;
import javax.swing.JFrame;
//import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
#SuppressWarnings("serial")
public class TeamManagerGUI extends JFrame implements ActionListener
{
// private JLabel pNameLabel = new JLabel("Player Name: "),
// pSchoolLabel = new JLabel("School: ");
// private JTextField pNameField = new JTextField(),
// pSchoolField = new JTextField();
private JButton addButton = new JButton("Add Player"),
removeButton = new JButton("Remove player");
private JPanel container = new JPanel(),
playerContainer = new JPanel();
int frameCounter = 1;
public TeamManagerGUI()
{
super("Team Manager User Interface");
setSize(1200,800);
setDefaultCloseOperation(EXIT_ON_CLOSE);
container.setLayout(new GridBagLayout());
playerContainer.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
addButton.addActionListener(this);
container.add(addButton,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
gbc.insets = new Insets(3,3,3,3);
container.add(removeButton,gbc);
this.add(container);
}
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
playerFrameArr.add(new JPanel());
gbc.gridx = 0;
gbc.gridy = 0;
playerContainer.add(new JButton("LABEL"),gbc);
gbc.gridx = 1;
gbc.gridy = 0;
playerContainer.add(new JButton("BUTTON"),gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter+1;
container.add(playerContainer,gbc);
System.out.println(frameCounter);
frameCounter++;
}
public void addPlayerRow()
{
playerFrame();
container.revalidate();
container.repaint();
}
public void removePlayerRow()
{
//Not yet implemented
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource() == addButton)
{
addPlayerRow();
}
if(ae.getSource() == removeButton)
{
//Not yet implemented
}
}
}

You are adding the playerContainer again and again. I think you should actually use the newly created JPanel. This one should be populated and added to the main container.
Adding a single panel multiple times will not render properly as this screws up the layout. I think you need to keep a reference to the new JPanel and fill this one with your layout and the buttons.
I am thinking something like this:
public void playerFrame()
{
GridBagConstraints gbc = new GridBagConstraints();
JPanel newPanel = new JPanel(new GridBagLayout());
playerFrameArr.add(newPanel);
gbc.gridx = 0;
gbc.gridy = 0;
newPanel.add(new JButton("LABEL"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
newPanel.add(new JButton("BUTTON"), gbc);
gbc.gridx = 0;
gbc.gridy = frameCounter + 1;
container.add(newPanel, gbc);
System.out.println(frameCounter);
frameCounter++;
}

Related

Java Swing - Change number of text fields based on a variable

I'd like to have a GUI that can adapt to user input, rather than making a different panel for each option.
The first panel has a number of buttons to choose from, each will bring you to the next panel that will contain text entry fields.
Option A: Has 2 components and should open a panel with 4 text fields.
Option B: Has 3 components and should open a panel with 6 text fields.
Specifically, option A is a recipe with two components, and option B is a recipe with 3 components. Each component has a lot number and an expiration date. So both panels will have the same two types of fields: lot number and expiration date. The number and names of components is what will change.
Can I have the same panel be able to adapt to a number of components sent to it based on which of the two options was selected? Or do I have to make two separate panels, one with 4 fields and one with 6?
Here's one idea:
Map<String, JTextField> fieldMap = new HashMap<String, JTextField>()
for(int i = 0; i < recipe.length; i++)
{
fieldMap.put("field" + i, new JTextField());
}
Idea derived from Creating a variable name using a String value
The code below addresses specifically your question statement, although I can't help thinking that you probably want something more generic, i.e. where there are more than two options. Also, the below code is only one possible implementation of your stated requirements.
The idea in the below code is to initially create all the required GUI components in a single container and simply change the visibility of the [optional] components depending on the selected option.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerDateModel;
public class Opciones implements ActionListener {
private JFrame frame;
private JLabel expiryThirdLabel;
private JLabel lotThirdLabel;
private JRadioButton twoRadioButton;
private JRadioButton threeRadioButton;
private JSpinner expiryFirstSpinner;
private JSpinner expirySecondSpinner;
private JSpinner expiryThirdSpinner;
private JTextField lotFirstTextField;
private JTextField lotSecondTextField;
private JTextField lotThirdTextField;
public void actionPerformed(ActionEvent event) {
Object src = event.getSource();
boolean flag;
if (twoRadioButton == src) {
flag = false;
}
else if (threeRadioButton == src) {
flag = true;
}
else {
flag = false;
JOptionPane.showMessageDialog(frame,
"Unrecognized source.",
"WARNING",
JOptionPane.WARNING_MESSAGE);
}
expiryThirdLabel.setVisible(flag);
expiryThirdSpinner.setVisible(flag);
lotThirdLabel.setVisible(flag);
lotThirdTextField.setVisible(flag);
frame.pack();
}
private void createAndDisplayGui() {
frame = new JFrame("Options");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createTopPanel(), BorderLayout.PAGE_START);
frame.add(createForm(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createForm() {
JPanel form = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.LINE_START;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets.bottom = 5;
gbc.insets.left = 5;
gbc.insets.right = 5;
gbc.insets.top = 5;
JLabel lotFirstLabel = new JLabel("Lot Number");
form.add(lotFirstLabel, gbc);
gbc.gridx = 1;
lotFirstTextField = new JTextField(6);
form.add(lotFirstTextField, gbc);
gbc.gridx = 2;
JLabel expiryFirstLabel = new JLabel("Expiry");
form.add(expiryFirstLabel, gbc);
gbc.gridx = 3;
expiryFirstSpinner = createSpinner();
form.add(expiryFirstSpinner, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
JLabel lotSecondLabel = new JLabel("Lot Number");
form.add(lotSecondLabel, gbc);
gbc.gridx = 1;
lotSecondTextField = new JTextField(6);
form.add(lotSecondTextField, gbc);
gbc.gridx = 2;
JLabel expirySecondLabel = new JLabel("Expiry");
form.add(expirySecondLabel, gbc);
gbc.gridx = 3;
expirySecondSpinner = createSpinner();
form.add(expirySecondSpinner, gbc);
gbc.gridx = 0;
gbc.gridy = 2;
lotThirdLabel = new JLabel("Lot Number");
lotThirdLabel.setVisible(false);
form.add(lotThirdLabel, gbc);
gbc.gridx = 1;
lotThirdTextField = new JTextField(6);
lotThirdTextField.setVisible(false);
form.add(lotThirdTextField, gbc);
gbc.gridx = 2;
expiryThirdLabel = new JLabel("Expiry");
expiryThirdLabel.setVisible(false);
form.add(expiryThirdLabel, gbc);
gbc.gridx = 3;
expiryThirdSpinner = createSpinner();
expiryThirdSpinner.setVisible(false);
form.add(expiryThirdSpinner, gbc);
return form;
}
private JSpinner createSpinner() {
SpinnerDateModel sdm = new SpinnerDateModel();
JSpinner spinner = new JSpinner(sdm);
spinner.setEditor(new JSpinner.DateEditor(spinner, "MM/dd/yyyy")); // USA format
return spinner;
}
private JPanel createTopPanel() {
JPanel topPanel = new JPanel();
JLabel label = new JLabel("Number of Components");
topPanel.add(label);
ButtonGroup buttonGroup = new ButtonGroup();
twoRadioButton = new JRadioButton("Two");
twoRadioButton.addActionListener(this);
twoRadioButton.setSelected(true);
buttonGroup.add(twoRadioButton);
topPanel.add(twoRadioButton);
threeRadioButton = new JRadioButton("Three");
threeRadioButton.addActionListener(this);
buttonGroup.add(threeRadioButton);
topPanel.add(threeRadioButton);
return topPanel;
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Opciones().createAndDisplayGui());
}
}
Initially, the GUI looks like this
And after selecting Three radio button
Refer to the following.
How to Use Buttons, Check Boxes, and Radio Buttons
How to Make Frames (Main Windows)
How to Use Spinners
How to Use GridBagLayout
How to Write an Action Listener

JPanel in different class, is what I did bad ? why?

I made a new class that extended JFrame and new class that extended JPanel to make the swing GUI. It is great, I like this due to its ease of readability.
However, when it comes to event handling things started getting complex. What I did really doesn't really seem like a solution; just like breaking good habit to make something work. How do I make this work properly?
This is my JFrame class
public class MainFrame extends JFrame{
private JTextArea textArea;
public MainFrame(String title){
super(title);
//set layout
setLayout(new BorderLayout());
//create components
JButton buttonOne = new JButton("click me");
textArea = new JTextArea();
JPanel detailedPanel = new leftPanel();
//add to panel
Container c = getContentPane();
c.add(buttonOne, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(detailedPanel, BorderLayout.WEST);
//Event Listening
leftPanel.buttonAdd.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
textArea.setText(textArea.getText() + " " + leftPanel.fieldName.getText() + " : " + leftPanel.fieldOccupation.getText());
}
});
}
}
this is my JPanel
public class leftPanel extends JPanel {
public static JTextField fieldName;
public static JTextField fieldOccupation;
public static JButton buttonAdd;
public leftPanel(){
Dimension panelSize = getPreferredSize();
panelSize.width = 250;
setPreferredSize(panelSize);
setBorder(BorderFactory.createTitledBorder("Personal Info"));
//labels
JLabel labelName = new JLabel("name: ");
JLabel labelOccupation = new JLabel("Occupation: ");
//textFields
fieldName = new JTextField(10);
fieldOccupation = new JTextField(10);
//buttons
buttonAdd = new JButton("Add !");
//actions
buttonAdd.addActionListener(new ActionListener(){
//on click
public void actionPerformed(ActionEvent e) {
String name = fieldName.getText();
String occupation = fieldOccupation.getText();
System.out.print(name + ": " + occupation);
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//// First Y add //////////////////////////////////////
//label NAME
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
add(labelName, gbc);
//label Occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 1;
add(labelOccupation, gbc);
//// SECOND Y add /////////////////////////////////////
//text field name
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 0;
add(fieldName, gbc);
//text feld occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 1;
add(fieldOccupation, gbc);
//// THIRD Y add //////////////////////////////////////
//add button
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.weightx = 1;
gbc.weighty = 10;
add(buttonAdd, gbc);
}
}
For the most part, you component should be as self contained as possible, this would suggest that the component should be responsible for handling the events generated by it's immediate children.
This doesn't mean that the component won't then generate it's own events, but that the component manages it's immediate children itself.
You should try and avoid exposing your child components directly (using public fields or getters) or indirectly (through event objects), this invites possible misuse of those components by external sources, which is never going to be pleasant.
In your example, your first class only wants to known when something happens that would require it to update the text area.
This would suggest that the LeftPanel needs to generate some kind of event (maybe a ActionEvent) and provide a getter for anybody who might be interested to gain access to the information that the LeftPanel is managing.
For example...
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class LeftPanel extends JPanel {
private JTextField fieldName;
private JTextField fieldOccupation;
private JButton buttonAdd;
public LeftPanel() {
setBorder(BorderFactory.createTitledBorder("Personal Info"));
//labels
JLabel labelName = new JLabel("name: ");
JLabel labelOccupation = new JLabel("Occupation: ");
//textFields
fieldName = new JTextField(10);
fieldOccupation = new JTextField(10);
//buttons
buttonAdd = new JButton("Add !");
//actions
buttonAdd.addActionListener(new ActionListener() {
//on click
public void actionPerformed(ActionEvent e) {
fireActionPerformed();
}
});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
//// First Y add //////////////////////////////////////
//label NAME
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 0;
add(labelName, gbc);
//label Occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.weightx = 1;
gbc.weighty = 1;
gbc.gridx = 0;
gbc.gridy = 1;
add(labelOccupation, gbc);
//// SECOND Y add /////////////////////////////////////
//text field name
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 0;
add(fieldName, gbc);
//text feld occupation
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 2;
gbc.weighty = 1;
gbc.gridx = 1;
gbc.gridy = 1;
add(fieldOccupation, gbc);
//// THIRD Y add //////////////////////////////////////
//add button
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.gridx = 1;
gbc.gridy = 3;
gbc.weightx = 1;
gbc.weighty = 10;
add(buttonAdd, gbc);
}
public void addActionListener(ActionListener listener) {
listenerList.add(ActionListener.class, listener);
}
public void removeActionListener(ActionListener listener) {
listenerList.remove(ActionListener.class, listener);
}
protected void fireActionPerformed() {
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
if (listeners.length > 0) {
ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "PropertiesSet");
for (ActionListener listener : listeners) {
listener.actionPerformed(evt);
}
}
}
public String getPersonName() {
return fieldName.getText();
}
public String getPersonOccupation() {
return fieldOccupation.getText();
}
}
The LeftPanel here now manages the internal state of it's components (no static or public fields). It also provides a ActionListener support to provide notification to interested parties who can obtain the information the component is managing via getters
The MainFrame then simply uses an instance of LeftPanel and registers a ActionListener to it so it can be notified when the panel has been updated and uses the getters to obtain the information it's interested in.
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class MainFrame extends JFrame {
private JTextArea textArea;
public MainFrame(String title) {
super(title);
//set layout
setLayout(new BorderLayout());
//create components
JButton buttonOne = new JButton("click me");
textArea = new JTextArea();
LeftPanel detailedPanel = new LeftPanel();
//add to panel
Container c = getContentPane();
c.add(buttonOne, BorderLayout.SOUTH);
c.add(textArea, BorderLayout.CENTER);
c.add(detailedPanel, BorderLayout.WEST);
//Event Listening
detailedPanel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.append(textArea.getText() + " " + detailedPanel.getPersonName() + " : " + detailedPanel.getPersonOccupation() + "\n");
}
});
}
}
In OO, you want to encapsulate the logic and responsibility to the object and then, as required, from callbacks (such as a Observer Pattern) to provide notification to interested parties that some predefined state has changed. Then simply expose the information that the object is managing via getters (and where required, setters for others to change the information as required)

Component not appearing when adding to panel

So I'm trying to create a series of radio buttons and check boxes that are displayed as follows:
Radio Button
Check Box
Radio Button
Check Box
Radio Button
However, I'm still in the learning process for java and I was wondering if anyone could solve this problem. At the moment the buttons and boxes are being displayed in the correct location, however the first radio button ("Courier") is not being displayed for some reason. If you could perhaps describe the reason and a possible solution that'd be great.
Thanks
Updated Code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
public class Question2 {
public static void main(String[] args) {
MyFrame f = new MyFrame("Font Chooser");
f.init();
}
}
class MyFrame extends JFrame {
MyFrame(String title) {
super(title);
}
private JPanel mainPanel;
private GridBagConstraints gbc = 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);
gbc.gridx = 0;
gbc.gridy = 1;
JCheckBox cb = new JCheckBox("Bold");
gbLayout.setConstraints(cb, gbc);
mainPanel.add(cb);
gbc.gridy = 3;
gbLayout.setConstraints(cb, gbc);
cb = new JCheckBox("Italic");
mainPanel.add(cb);
gbc.gridx = 1;
gbc.gridy = 0;
JRadioButton rb = new JRadioButton("Times");
gbLayout.setConstraints(rb, gbc);
mainPanel.add(rb, gbc);
gbc.gridy = 2;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 4;
mainPanel.add(rb, gbc);
this.pack();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
3 issues
Y Coordinate not re-assigned to different value causing last 2 radio buttons to exist at same location
GridBagConstraints not being used for left-hand side components
setConstraints erroneously being used to set constraints
Resultant code:
public class GoodGridBagApp {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame("Font Chooser");
frame.add(getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
private JPanel getMainPanel() {
JPanel mainPanel = new JPanel();
GridBagConstraints gbc = new GridBagConstraints();
mainPanel.setLayout(new GridBagLayout());
mainPanel.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
gbc.gridx = 1;
gbc.gridy = 2;
JCheckBox cb = new JCheckBox("Bold");
mainPanel.add(cb, gbc);
gbc.gridy = 4;
cb = new JCheckBox("Italic");
mainPanel.add(cb, gbc);
gbc.gridx = 2;
gbc.gridy = 1;
JRadioButton rb = new JRadioButton("Times");
mainPanel.add(rb, gbc);
gbc.gridy = 3;
rb = new JRadioButton("Helvatica");
mainPanel.add(rb, gbc);
rb = new JRadioButton("Courier");
gbc.gridy = 5;
mainPanel.add(rb, gbc);
return mainPanel;
}
});
}
}
Read: How to Use GridBagLayout

Hiding a frame in java upon a button click

I am trying to hide a frame once a button is clicked. The "Register" button should open up a frame where a user can register, and that works, but I am trying to hide the previous frame and I can't figure out how to do it.
Here's my code:
MainPage.java
package Practice_1;
import java.awt.*;
import java.awt.Insets;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
/**
*
* #author Ivan
*/
public class MainPage extends JPanel
{
JButton regButton, logButton, listButton;
JLabel homeMessage;
GridBagConstraints gbc = new GridBagConstraints();
public MainPage()
{
setLayout(new GridBagLayout());
gbc.insets = new Insets(5,5,5,5);
homeMessage = new JLabel("Please select an option below:");
gbc.gridx = 0;
gbc.gridy = 0;
add(homeMessage, gbc);
regButton = new JButton("Register");
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
regButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
//System.out.println("clicked");
RegisterPage regFrame = new RegisterPage();
JFrame register = new JFrame();
register.setTitle("Registration");
register.setSize(300,200);
register.setVisible(true);
register.add(regFrame);
new MainPage().setVisible(false); / THIS DOES NOT WORK
}
});
add(regButton, gbc);
logButton = new JButton("Log in");
gbc.ipadx = 40;
gbc.gridx = 0;
gbc.gridy = 2;
add(logButton, gbc);
listButton = new JButton("Customer list");
gbc.ipadx = 40;
gbc.gridx = 0;
gbc.gridy = 3;
add(listButton, gbc);
JFrame home = new JFrame();
home.setTitle("Main menu");
home.setSize(300,200);
home.setResizable(false);
home.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
home.setVisible(true);
home.add (mainFrame);
}
public static void main(String[] args) {
// TODO code application logic here
MainPage mainFrame = new MainPage();
}
}
RegisterPage.java
package Practice_1;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
*
* #author Ivan
*/
public class RegisterPage extends JPanel {
//JButton regButton, logButton, listButton;
JLabel homeMessage;
GridBagConstraints gbc = new GridBagConstraints();
public RegisterPage()
{
setLayout(new GridBagLayout());
gbc.insets = new Insets(5,5,5,5);
homeMessage = new JLabel("Register new user:");
gbc.gridx = 0;
gbc.gridy = 0;
add(homeMessage, gbc);
}
}
Acording to your code you are trying to hide JPanel instead of JFrame. My suggestion is to use
public class MainPage extends JFrame
than instantiate your JPanel like this:
JPanel panel = new JPanel();
and to add components on that panel. To hide your MainPage you can call:
this.setVisible(false);
but it would be better if you use:
this.dispose();

Java/Swing: Trying to get BorderLayout to play nice with GridBagLayout

I'd like to have a window that has 3 menus, one tied to the left, another tied to the center and the last one tied to the right. Like this:
--------------------------------------------
-toolbar1---------toolbar2---------toolbar3-
--------------------------------------------
- -
- rest of the window does something here -
The problem I'm having is that this is the result I get:
--------------------------------------------
---------toolbar1toolbar2toolbar3-----------
--------------------------------------------
- -
- rest of the window does something here -
Here's some sample code (compiles and shows the problem):
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestClass extends JFrame {
public TestClass() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
final JPanel upper = new JPanel();
upper.setLayout(new GridBagLayout());
final GridBagConstraints gbc = new GridBagConstraints();
final JButton toolbar1 = new JButton("toolbar1");
final JButton toolbar2 = new JButton("toolbar2");
final JButton toolbar3 = new JButton("toolbar3");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
upper.add(toolbar1, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.CENTER;
upper.add(toolbar2, gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
upper.add(toolbar3, gbc);
add(upper, BorderLayout.NORTH);
final JPanel something = new JPanel();
something.setBackground(Color.WHITE);
something.setPreferredSize(new Dimension(600, 600));
something.repaint();
add(something, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
final TestClass test = new TestClass();
}
}
How can I fix it? I thought that by setting the anchor in the GridBagConstraints I'd take care of it, but that didn't work.
You forgot to add :
gbc.weightx = 1.0;
gbc.weighty = 1.0;
Your changed code should look like :
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TestClass extends JFrame {
public TestClass() {
super("test");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
final JPanel upper = new JPanel();
GridBagLayout gridbag = new GridBagLayout();
upper.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
final JButton toolbar1 = new JButton("toolbar1");
final JButton toolbar2 = new JButton("toolbar2");
final JButton toolbar3 = new JButton("toolbar3");
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.WEST;
upper.add(toolbar1, gbc);
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.CENTER;
upper.add(toolbar2, gbc);
gbc.gridx = 2;
gbc.anchor = GridBagConstraints.EAST;
gbc.gridwidth = GridBagConstraints.REMAINDER;
upper.add(toolbar3, gbc);
add(upper, BorderLayout.NORTH);
final JPanel something = new JPanel();
something.setBackground(Color.WHITE);
something.setPreferredSize(new Dimension(600, 600));
something.repaint();
add(something, BorderLayout.CENTER);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
final TestClass test = new TestClass();
}
}
It works.
If your toolbar looks like a BorderLayout (WEST, CENTER, EAST), why not use a BorderLayout instead of a GridBagLayout?
Anyway, if you insist on using GridBagLayout, set the weightx constraint for toolbar2 to 1. This tells the layout manager that, if more room is available, it should give it all to toolbar2.
gbc.weightx = 1;
upper.add(toolbar2, gbc);
gbc.weightx = 0;

Categories