Component not appearing when adding to panel - java

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

Related

Scrolled JLayer not behaving as a scrolled JPanel which it is supposed to replace

I'd like to decorate a JPanel with a JLayer, but am failing to understand why doing so messes up this panel being laid out inside a JScrollPane. The decorated component is supposed to act as a drop in replacement, but it does not appear to work in this case.
The following code creates two equivalent JPanels and puts them into another panel with CardLayout (so you may switch between them using the buttons). The only difference is that in one case the panel is decorated with a JLayer.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public class JLayerScroll extends JFrame {
public JLayerScroll() {
setTitle("Jumpy border");
setLayout(new BorderLayout());
setDefaultCloseOperation(EXIT_ON_CLOSE);
createGui();
setSize(400, 200);
setLocationRelativeTo(null);
}
private void createGui() {
JPanel mainPanel = new JPanel(new CardLayout());
// two panels ("label panels"), first one decorated, second one not
mainPanel.add(createSingleScrolledComponent(new JLayer<JPanel>(createLabelPanel(), new LayerUI<JPanel>())), WITH_JLAYER);
mainPanel.add(createSingleScrolledComponent(createLabelPanel()), WITHOUT_JLAYER);
add(mainPanel);
createButtons(mainPanel);
}
private JPanel createSingleScrolledComponent(Component component) {
GridBagConstraints gbc;
JScrollPane scroll;
JPanel panel = new JPanel(new GridBagLayout());
scroll = new JScrollPane(component);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1.0d;
gbc.weighty = 1.0d;
panel.add(scroll, gbc);
return panel;
}
private JPanel createLabelPanel() {
GridBagConstraints gbc;
JPanel panel = new JPanel(new GridBagLayout());
JPanel entry = new JPanel(new GridBagLayout());
entry.setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.red));
JLabel label = new JLabel("Some input:");
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
entry.add(label, gbc);
JTextField field = new JTextField(20);
field.setMinimumSize(new Dimension(field.getPreferredSize().width, field.getMinimumSize().height));
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
entry.add(field, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 2;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
entry.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
panel.add(entry, gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0d;
panel.add(Box.createVerticalGlue(), gbc);
return panel;
}
private static final String WITH_JLAYER = "with-jlayer";
private static final String WITHOUT_JLAYER = "no-jlayer";
private void createButtons(final JPanel mainPanel) {
GridBagConstraints gbc;
JButton button;
JPanel actionsPanel = new JPanel(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1.0d;
actionsPanel.add(Box.createHorizontalGlue(), gbc);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
button = new JButton("With JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITH_JLAYER);
}
});
actionsPanel.add(button, gbc);
gbc.gridx = 2;
gbc.gridy = 0;
button = new JButton("Without JLayer");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CardLayout layout = (CardLayout) mainPanel.getLayout();
layout.show(mainPanel, WITHOUT_JLAYER);
}
});
actionsPanel.add(button, gbc);
add(actionsPanel, BorderLayout.SOUTH);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new JLayerScroll().setVisible(true);
}
});
}
}
If you pay attention to the red border in the two cases, you will notice that in one case it spans the whole available horizontal space (as expected), while in the other case, it only spans around visible components (label and text field).
Why is this happening and how do I achieve the same behavior as in the undecorated case (spanning through all available horizontal space)?
The only difference is that in one case the panel is decorated with a JLayer.
A difference between a JPanel and a JLayer is that the JLayer implements the Scrollable interface but a JPanel does not.
The getScrollableTracksViewportWidth() method controls whether the component added to the viewport should be displayed at its preferred size or the width of the viewport. The JLayer delegates to the JPanel, but since JPanel doesn't implement the Scrollable interface the JLayer implementation will return "false" which means the component should be displayed at its preferred width.
So a way to get around this is to use a wrapper panel for the JLayer:
//scroll = new JScrollPane(component);
JPanel wrapper = new JPanel( new BorderLayout() );
wrapper.add( component );
scroll = new JScrollPane(wrapper);
Now the component added to the viewport of the scrollpane is a JPanel in both cases, so they should behave the same way.

How Do You Fix the alignment of GridBagLayout?

I'd like to ask something about GridBagLayout because whenever I try to put the lblStudentID under lblName it just makes an output wherein it stays in the right side of lblName
import javax.swing.*;
import java.awt.*;
public class Student extends JPanel {
JLabel picture;
JLabel lblStudentID = new JLabel("Student ID:");
JLabel lblName = new JLabel("Name:");
JLabel lblProg = new JLabel("Program:");
JLabel lblGen = new JLabel("Gender:");
JPanel panel = new JPanel();
JRadioButton rbtn1 = new JRadioButton("Male");
JRadioButton rbtn2 = new JRadioButton("Female");
JComboBox cmbProg = new JComboBox();
TextField txtStudentID = new TextField();
TextField txtName = new TextField();
GridBagConstraints gbc = new GridBagConstraints();
public void setName() {
}
public Student() {
setLayout(new GridBagLayout());
picture = new JLabel(createImageIcon("images/student.jpg"));
picture.setSize(100, 100);
add(picture);
add(lblName, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
add(txtName, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(lblStudentID, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(txtStudentID, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Student");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Display the window.
Student LoginPane = new Student();
LoginPane.setOpaque(true); // content panes must be opaque
LoginPane.setLayout(new FlowLayout());
LoginPane.setBackground(Color.white);
frame.setContentPane(LoginPane);
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = Student.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
First you change the GridBagConstraints too late.
gbc.gridx = 0;
gbc.gridy = 0;
add(lblName,gbc);
gbc.gridx = 1;
gbc.gridy = 0;
add(txtName,gbc);
gbc.gridx = 0;
gbc.gridy = 1;
add(lblStudentID,gbc);
gbc.gridx = 1;
gbc.gridy = 1;
add(txtStudentID,gbc);
Second you change the layout back to FlowLayout of your LoginPane.
Edit
I have stripped-down your code. Maybe this will help you:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.TextField;
import java.net.URL;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Student extends JPanel {
private static final long serialVersionUID = 8923497527096438302L;
private JLabel picture;
private JLabel lblStudentID = new JLabel("Student ID:");
private JLabel lblName = new JLabel("Name:");
TextField txtStudentID = new TextField();
TextField txtName = new TextField();
public Student() {
setLayout(new BorderLayout());
setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
setBackground(Color.WHITE);
JPanel formPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
formPanel.setOpaque(false);
picture = new JLabel(createImageIcon("images/student.jpg"));
picture.setPreferredSize(new Dimension(100, 100));
picture.setBorder(BorderFactory.createLineBorder(Color.black));
gbc.fill = GridBagConstraints.BOTH;
gbc.gridy = 0;
formPanel.add(picture, gbc);
gbc.gridy = 1;
gbc.gridwidth = 1;
formPanel.add(lblName, gbc);
gbc.gridy = 1;
gbc.weightx = 1;
formPanel.add(txtName, gbc);
gbc.weightx = 0;
gbc.gridy = 2;
formPanel.add(lblStudentID, gbc);
gbc.gridy = 2;
formPanel.add(txtStudentID, gbc);
add(formPanel, BorderLayout.PAGE_START);
}
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Student");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
// Display the window.
new Student().setBackground(Color.white);
frame.setContentPane(new Student());
frame.setVisible(true);
}
protected static ImageIcon createImageIcon(String path) {
URL imgURL = Student.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Dynamicly adding JPanels to a JFrame

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

Is it possible to make the elements inside a JPanel with GridBagLayout to start from the top left?

I have a Swing Form that contains a JScrollPane(activityScrollPane) for a JPanel(activityPanel). The panel contains a JTextField and a JButton (that is used to add more fields to the Panel). Now the problem is that the elements start from the center of the panel as in the image below (with the borders marking the activityScrollPane boundary)
Following is the code I am currently using to make the scroll pane and associated components.
//part of the code for creating the ScrollPane
final JPanel activityPanel = new JPanel(new GridBagLayout());
gbc.gridx=0;
gbc.gridy=0;
JScrollPane activityScrollPane = new JScrollPane(activityPanel);
//adding activity fields
activityFields = new ArrayList<JTextField>();
fieldIndex = 0;
activityFields.add(new JTextField(30));
final GridBagConstraints activityGBC = new GridBagConstraints();
activityGBC.gridx=0;
activityGBC.gridy=0;
activityGBC.anchor = GridBagConstraints.FIRST_LINE_START;
activityPanel.add(activityFields.get(fieldIndex),activityGBC);
fieldIndex++;
JButton btn_more = (new JButton("more"));
activityGBC.gridx=1;
activityPanel.add(btn_more,activityGBC);
How can I make the JTextField and the JButton or for that matter any component to appear on the top left corner of the JScrollPane. I have already tried using
activityConstraints.anchor = GridBagConstraints.NORTHWEST;
as pointed in the SO post, but it does not at all seem to work.
You simply forgot to provide any weightx/weighty values, atleast one having a non-zero value will do. have a look at this code example :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
frame.setContentPane(contentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Latest EDIT : No spacing along Y-Axis
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutDemo
{
private JTextField tfield1;
private JButton button1;
private JTextField tfield2;
private JButton button2;
private void displayGUI()
{
JFrame frame = new JFrame("GridBagLayout Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new GridBagLayout());
tfield1 = new JTextField(10);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.weightx = 1.0;
//gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield1, gbc);
button1 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button1, gbc);
tfield2 = new JTextField(10);
gbc.weightx = 1.0;
gbc.weighty = 0.2;
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
contentPane.add(tfield2, gbc);
button2 = new JButton("More");
gbc.gridx = 1;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.NONE;
contentPane.add(button2, gbc);
JScrollPane scroller = new JScrollPane(contentPane);
frame.add(scroller);
frame.pack();
frame.setVisible(true);
}
public static void main(String... args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new GridBagLayoutDemo().displayGUI();
}
});
}
}
Sorry as my answer me be on the off-side of what you have asked, but why dont you use GroupLayout instead of GridBag Layout, thats much more easier to handle
try it with BorderLayout: controls.setLayout(new BorderLayout()); and then apply it for your JPanel controls.add(yourPanel, BorderLayout.PAGE_START);
I also have problems with GridBagLayout so i solved it with BorderLayout and it works so fine.
So i wrote for your little example:
private void initComponents() {
controls = new Container();
controls = getContentPane();
controls.setLayout(new BorderLayout());
panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
field = new JTextField(20);
c.gridx = 0;
c.gridy = 0;
panel.add(field, c);
one = new JButton("Go!");
c.gridx = 1;
c.gridy = 0;
panel.add(one, c);
controls.add(panel, BorderLayout.PAGE_START);
}
Hope it helps!
I think this could be simple and possible, you can
put Nested JPanel to the JScrollPane
to this JPanel
put JPanels contains JComponent to the GridLayout (notice about scrolling, you have to change scrolling increment)
or use most complex JComponents as
put JPanels contains JComponent as Item to the JList
put JPanels contains JComponent as row to the JTable (with only one Column, with or without TableHeader)
Add one panel at the right and one at the bottom.
Right Panel:
Set Weight X to 1.0.
Set Fill to horizontal.
Bottom Panel:
Set Weight Y to 1.0.
Set Fill to vertical
There may be better ways to that, but this one worked for me.

Java 2 JPanel's in one JFrame layout

Hi I am trying to add 2 JPanel's to a JFrame that take the full width and height of the JFrame.I managed to add them with GridBagLayout() but I can't seem to set the size of the JPanels using the setsize().I have also tryied to used ipady and ipadx while that seemed to work at first after I aded some buttons the whole layout became a mess.Here is my code:
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setVisible(true);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
tradeframe.setLayout(new GridBagLayout());
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
GridBagConstraints a = new GridBagConstraints();
a.gridx = 0;
a.gridy = 0;
a.weightx = 360;
a.weighty = 300;
//a.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P1panel , a);
GridBagConstraints b = new GridBagConstraints();
b.gridx = 1;
b.gridy = 0;
b.weightx = 360;
b.weighty = 300;
// b.fill = GridBagConstraints.HORIZONTAL;
tradeframe.add(P2panel , b);
How can I make that each JPanel is 300px width and 400px in height?
for GridBaglayout you have to set
fill
anchor
weightx and weighty
gridx / gridy (depend of orientations)
then is possible for example
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class BorderPanels extends JFrame {
private static final long serialVersionUID = 1L;
public BorderPanels() {
setLayout(new GridBagLayout());// set LayoutManager
GridBagConstraints gbc = new GridBagConstraints();
JPanel panel1 = new JPanel();
Border eBorder = BorderFactory.createEtchedBorder();
panel1.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridx = gbc.gridy = 0;
gbc.gridwidth = gbc.gridheight = 1;
gbc.fill = GridBagConstraints.BOTH;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.weightx = gbc.weighty = 20;
add(panel1, gbc); // add compoenet to the COntentPane
JPanel panel2 = new JPanel();
panel2.setBorder(BorderFactory.createTitledBorder(eBorder, "60pct"));
gbc.gridy = 1;
gbc.weightx = gbc.weighty = 60;
//gbc.insets = new Insets(2, 2, 2, 2);
add(panel2, gbc); // add component to the COntentPane
JPanel panel3 = new JPanel();
panel3.setBorder(BorderFactory.createTitledBorder(eBorder, "20pct"));
gbc.gridy = 2;
gbc.weightx = gbc.weighty = 20;
gbc.insets = new Insets(2, 2, 2, 2);
add(panel3, gbc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // important
pack();
setVisible(true); // important
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() { // important
public void run() {
BorderPanels borderPanels = new BorderPanels();
}
});
}
}
on most cases will be better use another LayoutManager
JFrame tradeframe = new JFrame("Trade");
JPanel P1panel = new JPanel();
P1panel.setBackground(Color.red);
JPanel P2panel = new JPanel();
P2panel.setBackground(Color.BLACK);
tradeframe.setSize(600, 400);
tradeframe.setResizable(false);
tradeframe.setLocationRelativeTo(null);
Box content = new Box(BoxLayout.X_AXIS);
P1panel.add(new JButton ("P1 Agree"));
P2panel.add(new JButton ("P2 Agree"));
content.add(P1panel);
content.add(P2panel);
tradeframe.setContentPane(content);
tradeframe.setVisible(true);
Invoke setPreferredSize(new Dimension(int width, int height)); method on your panel objects.
Here is the way to do that :
import java.awt.*;
import javax.swing.*;
public class GridBagLayoutTest
{
public GridBagLayoutTest()
{
JFrame frame = new JFrame("GridBag Layout Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
Container container = frame.getContentPane();
container.setLayout(new GridBagLayout());
JPanel leftPanel = new JPanel();
leftPanel.setBackground(Color.WHITE);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_START;
gbc.fill = GridBagConstraints.BOTH;
container.add(leftPanel, gbc);
JPanel rightPanel = new JPanel();
rightPanel.setBackground(Color.BLUE);
gbc = new GridBagConstraints();
gbc.gridx = 1;
gbc.gridy = 0;
gbc.weightx = 0.5;
gbc.weighty = 1.0;
gbc.anchor = GridBagConstraints.FIRST_LINE_END;
gbc.fill = GridBagConstraints.BOTH;
container.add(rightPanel, gbc);
frame.setSize(600, 400);
frame.setVisible(true);
}
public static void main(String... args)
{
Runnable runnable = new Runnable()
{
public void run()
{
new GridBagLayoutTest();
}
};
SwingUtilities.invokeLater(runnable);
}
}
OUTPUT :
You are using setSize() instead of setPreferredSize(). The difference is somewhat misleading and I would consider it a gotcha in java. Some more information about what the difference between the two can be found here.
The article I link has some other pitfalls/gotchas and a useful read if you are new to Java.

Categories