How to get CardLayout implemented properly with Eclipse WindowBuilder? - java

So using WindowBuilder (latest version of Ecliple, Kepler) I've created a frame as so:
But I'd like to switch between them with a button, which I've created on the panelWelcome.
I'm guessing I'd add an itemListener, then create a method that switches between the cards.
The problem is, I have no idea how to proceed after that. Here's the code that's automatically generated:
package client;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.CardLayout;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
public class Test {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
JPanel panelWelcome = new JPanel();
frame.getContentPane().add(panelWelcome, "name_98933171901972");
GridBagLayout gbl_panelWelcome = new GridBagLayout();
gbl_panelWelcome.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
gbl_panelWelcome.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
gbl_panelWelcome.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panelWelcome.setLayout(gbl_panelWelcome);
JLabel lblTitle = new JLabel("MEMEPlayer");
lblTitle.setFont(new Font("Segoe UI", Font.BOLD, 12));
GridBagConstraints gbc_lblTitle = new GridBagConstraints();
gbc_lblTitle.insets = new Insets(0, 0, 5, 0);
gbc_lblTitle.gridx = 5;
gbc_lblTitle.gridy = 0;
panelWelcome.add(lblTitle, gbc_lblTitle);
JLabel lblNewLabel = new JLabel("Welcome! To get started, select a movie from the drop down menu");
lblNewLabel.setFont(new Font("Segoe UI", Font.PLAIN, 11));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.gridx = 5;
gbc_lblNewLabel.gridy = 2;
panelWelcome.add(lblNewLabel, gbc_lblNewLabel);
JComboBox comboBox = new JComboBox();
comboBox.setModel(new DefaultComboBoxModel(new String[] {"The Avengers (2012)", "Monsters, Inc. (2001)", "Prometheus (2012)"}));
GridBagConstraints gbc_comboBox = new GridBagConstraints();
gbc_comboBox.insets = new Insets(0, 0, 5, 0);
gbc_comboBox.gridx = 5;
gbc_comboBox.gridy = 4;
panelWelcome.add(comboBox, gbc_comboBox);
JButton btnNewButton = new JButton("Next >");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.insets = new Insets(0, 0, 5, 0);
gbc_btnNewButton.gridx = 5;
gbc_btnNewButton.gridy = 6;
btnNewButton.addItemListener((ItemListener) this);
panelWelcome.add(btnNewButton, gbc_btnNewButton);
JLabel lblNewLabel_1 = new JLabel("");
lblNewLabel_1.setIcon(new ImageIcon("C:\\temp\\Meme1\\largeVLC.png"));
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.gridx = 5;
gbc_lblNewLabel_1.gridy = 8;
panelWelcome.add(lblNewLabel_1, gbc_lblNewLabel_1);
JPanel panelVideo = new JPanel();
frame.getContentPane().add(panelVideo, "name_98968999152440");
}
}
Thanks for any help!

The problem I see you're facing is that you are setting the layout to the frame. This is a problem because it means that the frame can only have on visible component at a time. That component being one of the panels. So you can put a button. The button would have to be on the one of the panels, which may be hard to maintain, in terms of navigation.
So instead, have a main JPanel that has the CardLayout, and add your card panels to that main panel. Then you can add the main panel to the frame, along with buttons for navigation.
Another option is to have a menu bar with option to change the cards, then that way, you can keep the card layout on the frame, because navigation is controlled by the menu options.
See How to Use CardLayout if you're not really sure even how to use CardLayout, hand coding. You're going to need a reference to layout and call one of its navigation methods like show(), next(), or previous()
You may also find this post interesting. It used Netbeans, but maybe you'll pick something up

Related

Controlling the image quality on the Java application side

I posted a question here asking about what to do about a blurry picture in a java application. What i discovered is that my windows scaling was causing the blurriness. Now i have a greater issue. I want the quality of the image and application to be controlled via the application, without having to change any windows settings if at all possible.
Instead of changing the scaling back to 100% there was another windows suggestion from here that said to change the compatibility settings of the java.exe and or javaw.exe to override the high DPI settings to have scaling performed by the system. It works, as in the picture is clearer, but the text loses a crispness to it.
The best quality i have found for the application is to have it not override the high DPI but simply have the scaling set to 100%. The text is crisp and clear and the picture is as well.
I am trying to figure out if there is a way to keep that quality without having to have the users change any of their windows settings to have the application look good. I'm wondering if there is a way in the code to achieve this.
here is an example program with my scaling at 125% The picture is blurry but the text good.
Here is an example of the DPI overridden by the system with scaling still at 125% notice that the text loses a crispness to it but the picture is better.
finally the scaling is 100% and the DPI is not being overridden anymore. this is the best text and picture quality
here is the example code, if anyone needs it.
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Color;
import java.awt.Component;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import java.awt.Insets;
import java.awt.Font;
import java.awt.Dimension;
import javax.swing.JTextArea;
#SuppressWarnings("serial")
public class example extends JFrame {
private JPanel contentPane;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
example frame = new example();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public example() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 558, 373);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0};
gbl_contentPane.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JPanel panel = new JPanel();
panel.setBackground(Color.WHITE);
GridBagConstraints gbc_panel = new GridBagConstraints();
gbc_panel.fill = GridBagConstraints.BOTH;
gbc_panel.gridx = 0;
gbc_panel.gridy = 0;
contentPane.add(panel, gbc_panel);
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[]{0, 0, 0};
gbl_panel.rowHeights = new int[]{0, 0, 0, 100, 0};
gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
gbl_panel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
panel.setLayout(gbl_panel);
JLabel lblWordsGoHere = new JLabel("Words go here");
lblWordsGoHere.setFont(new Font("Cambria Math", Font.PLAIN, 18));
GridBagConstraints gbc_lblWordsGoHere = new GridBagConstraints();
gbc_lblWordsGoHere.insets = new Insets(0, 0, 5, 0);
gbc_lblWordsGoHere.gridx = 1;
gbc_lblWordsGoHere.gridy = 0;
panel.add(lblWordsGoHere, gbc_lblWordsGoHere);
Component horizontalStrut = Box.createHorizontalStrut(20);
horizontalStrut.setPreferredSize(new Dimension(20, 20));
GridBagConstraints gbc_horizontalStrut = new GridBagConstraints();
gbc_horizontalStrut.insets = new Insets(0, 0, 5, 5);
gbc_horizontalStrut.gridx = 0;
gbc_horizontalStrut.gridy = 1;
panel.add(horizontalStrut, gbc_horizontalStrut);
JLabel lblNewLabel = new JLabel("More words here...");
lblNewLabel.setFont(new Font("Cambria Math", Font.PLAIN, 14));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel.anchor = GridBagConstraints.WEST;
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 1;
panel.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_1 = new JLabel(new ImageIcon(example.class.getResource("/icons/Step3.png")));
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_1.gridx = 1;
gbc_lblNewLabel_1.gridy = 2;
panel.add(lblNewLabel_1, gbc_lblNewLabel_1);
JTextArea txtrLotsOfDescriptive = new JTextArea();
txtrLotsOfDescriptive.setLineWrap(true);
txtrLotsOfDescriptive.setWrapStyleWord(true);
txtrLotsOfDescriptive.setEditable(false);
txtrLotsOfDescriptive.setFont(new Font("Cambria Math", Font.PLAIN, 14));
txtrLotsOfDescriptive.setText("Lorem ipsum dolor sit amet, eu tempor maluisset eum. Ipsum detracto mediocrem quo eu. Eos ad ocurreret argumentum. Cum ei vero ipsum alienum, has sonet impetus repudiandae at, cu viris assentior eum.");
GridBagConstraints gbc_txtrLotsOfDescriptive = new GridBagConstraints();
gbc_txtrLotsOfDescriptive.fill = GridBagConstraints.BOTH;
gbc_txtrLotsOfDescriptive.gridx = 1;
gbc_txtrLotsOfDescriptive.gridy = 3;
panel.add(txtrLotsOfDescriptive, gbc_txtrLotsOfDescriptive);
}
}

Another GridBagLayout Alignment

I read a lot about this problem here... But I just don't seem to get how to solve this.
All the solutions I tried are not working.
But let's start at the beginning:
I'm building my interface with Swing and trying to be modular.
So I've got a class (extending JPanel) for my left Main Menu.
The Menu is built with several buttons in a GridBagLayout.
But I am not able to get this layout to aligned to the top of the window (panel).
Example: Label at the Top of the Panel, Text Field below, button below the text field, etc.
Please see my code:
public class LeftMenu extends JPanel {
public LeftMenu(){
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 86, 0 };
gbl_panel.rowHeights = new int[] {32, 32, 32, 32, 32, 32, 32, 32, 32 };
gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
setLayout(gbl_panel);
JLabel lblEnterTrunkId = new JLabel("Enter Trunk ID");
GridBagConstraints gbc_lblEnterTrunkId = new GridBagConstraints();
gbc_lblEnterTrunkId.fill = GridBagConstraints.HORIZONTAL;
gbc_lblEnterTrunkId.insets = new Insets(0, 0, 5, 0);
gbc_lblEnterTrunkId.gridx = 0;
gbc_lblEnterTrunkId.gridy = 0;
gbc_lblEnterTrunkId.anchor = GridBagConstraints.NORTH;
add(lblEnterTrunkId, gbc_lblEnterTrunkId);
}
}
There is a text field and some buttons following behind the Label.
But I assume, these are not relevant...
If they are... they are mostly looking like the Label (just that they are not Labels... I think you get me)
All guides I read, are all pointing to the anchor of the GridBagConstraint. It is there.... but not working.
It's wonderfully aligned in the middle of the panel.
If it does matter:
the Panel ist used as a LeftComponent of a SplitPane:
public LeftMenu leftpanel = new LeftMenu();
splitPaneTrunks.setLeftComponent(leftpanel);
Looking forward to your help.
Here is a picture of my side menu... centered horizontally. as it should not be.
Instead of using GridBagLayout, you could make a wrap using a JPanel with the layout BorderLayout, like so:
setLayout(new BorderLayout());
JPanel gridBagWrap = new JPanel();
GridBagLayout gbl_panel = new GridBagLayout();
gbl_panel.columnWidths = new int[] { 86, 0 };
gbl_panel.rowHeights = new int[] {32, 32, 32, 32, 32, 32, 32, 32, 32 };
gbl_panel.columnWeights = new double[] { 0.0, Double.MIN_VALUE };
gbl_panel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0 };
gridBagWrap.setLayout(gbl_panel);
JLabel lblEnterTrunkId = new JLabel("Enter Trunk ID");
GridBagConstraints gbc_lblEnterTrunkId = new GridBagConstraints();
gbc_lblEnterTrunkId.fill = GridBagConstraints.HORIZONTAL;
gbc_lblEnterTrunkId.insets = new Insets(0, 0, 5, 0);
gbc_lblEnterTrunkId.gridx = 0;
gbc_lblEnterTrunkId.gridy = 0;
gbc_lblEnterTrunkId.anchor = GridBagConstraints.NORTH;
gridBagWrap.add(lblEnterTrunkId, gbc_lblEnterTrunkId);
add(gridBagWrap, BorderLayout.NORTH);
here is a picture of my side menu... centered horizontally. as it should not be.
I think you mean it should not be centered vertically if you want the components displayed from the top.
In any case I think the problem is your weighty constraint. It needs to be non-zero for at least one of the components otherwise the components will be centered vertically.
Read the section from the Swing tutorial on How to Use GridBagLayout. There is a section on the weightx/weighty constraints that will explain this in more detail.
There is no surprise that you are lost with GridBagLayout manager.
It is in fact one of its most commonly mentioned features. GridBagLayout comes from the nineties and uses pixel-fixed gaps between components, which is not portable. With this manager, you have to tediously define each cell of the layout; no wonder people are confused.
I recommend to use MigLayout. And if it cannot be used, then GroupLayout.
Here is a solution with MigLayout:
package com.zetcode;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
/*
Demonstration of MigLayout manager.
Author: Jan Bodnar
Website: zetcode.com
*/
public class MigLayoutTrunkEx extends JFrame {
public MigLayoutTrunkEx() {
initUI();
}
private void initUI() {
JLabel lbl = new JLabel("Enter Trunk ID");
JTextField textField = new JTextField(10);
JButton btn1 = new JButton("A");
JButton btn2 = new JButton("B");
JButton btn3 = new JButton("C");
JButton btn4 = new JButton("D");
JButton btn5 = new JButton("E");
JTextArea area = new JTextArea(20, 25);
area.setBorder(BorderFactory.createEtchedBorder());
JLabel statusBar = new JLabel("Ready");
createLayout(lbl, textField, btn1, btn2, btn3,
btn4, btn5, area, statusBar);
setTitle("MigLayout example");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void createLayout(JComponent... arg) {
setLayout(new MigLayout("", "[align center]", ""));
add(arg[0], "split 7, flowy");
add(arg[1]);
add(arg[2]);
add(arg[3]);
add(arg[4]);
add(arg[5]);
add(arg[6]);
add(arg[7], "grow, push, wrap");
add(arg[8], "align left, growx, spanx");
pack();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
MigLayoutTrunkEx ex = new MigLayoutTrunkEx();
ex.setVisible(true);
});
}
}
It is easy, once you get to know MigLayout. Ten or fifteen minutes of work.
Screenshot:

JFrame Back Ground Image that other buttons don't appear on frame when background image is set? [duplicate]

This question already has answers here:
Setting background images in JFrame
(4 answers)
Closed 8 years ago.
I want to add a background image to my frame.But when i add an image to my frame it was added successfully but other things like j label and buttons added on frame afterwords don't appear on frame. i have kept image on Desktop. below is my code
package UI;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Color;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Font;
import javax.swing.JButton;
import java.awt.Insets;
public class EditTeamInterface extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
EditTeamInterface frame = new EditTeamInterface();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
//frame.getContentPane().setBackground(Color.white);
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Abdullah/Desktop/cricketBackGround1.jpg")))));
frame.pack();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public EditTeamInterface() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 624, 356);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
GridBagLayout gbl_contentPane = new GridBagLayout();
gbl_contentPane.columnWidths = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
gbl_contentPane.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_contentPane.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE};
contentPane.setLayout(gbl_contentPane);
JLabel lblNewLabel = new JLabel("EDIT OPTIONS");
lblNewLabel.setFont(new Font("SketchFlow Print", Font.BOLD, 18));
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
contentPane.add(lblNewLabel, gbc_lblNewLabel);
JButton btnNewButton = new JButton("New button");
GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
gbc_btnNewButton.gridx = 5;
gbc_btnNewButton.gridy = 5;
contentPane.add(btnNewButton, gbc_btnNewButton);
}
}
In the EditTeamInterface's constructor, you set the content pane for the frame using setContentPane(contentPane);, but in the static void main, you replace it with
frame.setContentPane(new JLabel(new ImageIcon(ImageIO.read(new File("C:/Users/Abdullah/Desktop/cricketBackGround1.jpg")))));
This discards everything you did before for this new content...
Instead of EditTeamInterface extending from JFrame, change it so that it extends from JPanel
Create a new instance of a JFrame, set the content pane to your label and then add EditTeamInterface to the frame.
Because JLabel has no layout manager by default, you should call setLayout(new BorderLayout()) on the frame after you set it's content pane to the label
While, using a JLabel, this way will work, JLabel will NOT calculate it's preferred size based on the needs of it's contents, but rather based on the properties of the icon and text. This doesn't really make it suitable for this task.
A better solution is to use a custom JPanel and override it's paintComponent to render the image you want. If you're clever, you will make it so that this class is re-usable.
Something like this for example

Nested Layouts (GridBagLayout inside a FlowLayout)

How can I position my labels with this code? It seems that gridbaglayout is not working here, especially the gridbagconstraints. Even if I change the gridx and gridy values, the labels are not moving.
I need to make it in like 3 even columns, 1 column = 1 panel
package nest;
import javax.swing.*;
import java.awt.*;
public class nested extends JFrame{
public static void main(String[] args) {
JFrame f=new JFrame("Bio Data");
JPanel p1=new JPanel(new GridBagLayout());
JPanel p2=new JPanel(new GridBagLayout());
//JPanel p3=new JPanel(new GridBagLayout());
GridBagConstraints c1=new GridBagConstraints();
GridBagConstraints c2=new GridBagConstraints();
JLabel l1=new JLabel("aa");
JLabel l2=new JLabel("bb");
c1.gridx=1;
c1.gridy=1;
p1.add(l1, c1);
c2.gridx=4;
c2.gridy=4;
p2.add(l2, c2);
f.add(p1);
f.add(p2);
f.setVisible(true);
f.setSize(800,500);
f.setResizable(false);
f.setLayout(new FlowLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Changing gridx and gridy does not change the actual position of the labels, but rather the order/format that the labels will be displayed in. If you have something in gridx 4 but nothing in gridx 1,2 or 3 then that object will be the first column.
Also, it woulld be very odd to put a new panel in each column since you can put things in different rows of the gridBagLayout. Here is a short example of a gridBagLayout inside a flowLayout with three different columns of labels:
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JLabel;
import java.awt.Insets;
public class nest extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
nest frame = new nest();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public nest() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new GridLayout(0, 1, 0, 0));
JPanel panel = new JPanel();
contentPane.add(panel);
panel.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
JPanel panel_1 = new JPanel();
panel.add(panel_1);
GridBagLayout gbl_panel_1 = new GridBagLayout();
gbl_panel_1.columnWidths = new int[]{0, 0, 27, 0};
gbl_panel_1.rowHeights = new int[]{0, 16, 0};
gbl_panel_1.columnWeights = new double[]{0.0, 0.0, 0.0, Double.MIN_VALUE};
gbl_panel_1.rowWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
panel_1.setLayout(gbl_panel_1);
JLabel lblNewLabel_1 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel_1.gridx = 0;
gbc_lblNewLabel_1.gridy = 0;
panel_1.add(lblNewLabel_1, gbc_lblNewLabel_1);
JLabel lblNewLabel = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
gbc_lblNewLabel.gridx = 1;
gbc_lblNewLabel.gridy = 0;
panel_1.add(lblNewLabel, gbc_lblNewLabel);
JLabel lblNewLabel_2 = new JLabel("New label");
GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
gbc_lblNewLabel_2.insets = new Insets(0, 0, 5, 0);
gbc_lblNewLabel_2.gridx = 2;
gbc_lblNewLabel_2.gridy = 0;
panel_1.add(lblNewLabel_2, gbc_lblNewLabel_2);
JLabel lblLabel = new JLabel("New label");
GridBagConstraints gbc_lblLabel = new GridBagConstraints();
gbc_lblLabel.gridx = 2;
gbc_lblLabel.gridy = 1;
panel_1.add(lblLabel, gbc_lblLabel);
}
}
I created this with the Google WindowBuilder. Note that you don't necessarily need to set the columnWidths, rowHeights, columnWeights, or rowWeights (and it is better not to sometimes when you have dynamic content). Hopefully this helps.

Problems with GridBagLayout

I cant transfer any of the relatet posts to my simple problem.
In order to get into GridBagLayout i wrote a simple example:
JFrame frame = new JFrame();
JPanel main =new JPanel();
frame.setContentPane(main);
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
main.setLayout(gbl);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
gbc.gridx=0;
gbc.gridy=0;
gbc.gridheight=1;
gbc.gridwidth=1;
gbc.fill=GridBagConstraints.WEST;
gbl.setConstraints(btn1, gbc);
gbc.gridx=0;
gbc.gridy=1;
gbl.setConstraints(btn2, gbc);
frame.setSize(new Dimension(200,100));
main.add(btn1);
main.add(btn2);
frame.setVisible(true);
Here i have the Problem that neither .fill nor any other parameter of GBConstrains sems to work. I ever get the two buttons in the middle of the window.
thx in advance
Your configuration of your GridBagConstraint are incorrect:
fill can only take: NONE, VERTICAL, HORIZONTAL or BOTH.
anchor can use relative location within a "cell"
fill and anchor almost always require to use weightx/weighty
Try to avoid using gridx and gridy because they get hard to maintain. Instead use their default value (RELATIVE) and you can change the value of gridwidth/gridheight to set it to 1 (or more if needed) and REMAINDER to make the layout wrap to next line/column (components are then positionned in the order they were added to the container.
Here is a working code of yours (although I am not sure of the exact layout you were targetting):
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestGBL {
protected void initUI() {
JFrame frame = new JFrame();
GridBagLayout gbl = new GridBagLayout();
JPanel main = new JPanel(gbl);
frame.setContentPane(main);
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1.0;
main.setLayout(gbl);
JButton btn1 = new JButton("1");
JButton btn2 = new JButton("2");
gbl.setConstraints(btn1, gbc);
gbl.setConstraints(btn2, gbc);
main.add(btn1);
main.add(btn2);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestGBL().initUI();
}
});
}
}
Edit: I made a sample application that demonstrates how to use GridBadLayout that is reusing the constraints:
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Test1 {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test1 window = new Test1();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Test1() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, 0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JButton btnTest = new JButton("Test1");
GridBagConstraints gbc_btnTest = new GridBagConstraints();
gbc_btnTest.insets = new Insets(0, 0, 0, 5);
gbc_btnTest.gridx = 0;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest, gbc_btnTest);
JButton btnTest_1 = new JButton("Test2");
gbc_btnTest.gridx = 1;
gbc_btnTest.gridy = 0;
frame.getContentPane().add(btnTest_1, gbc_btnTest);
}
}

Categories

Resources