How top-align side-by-side panels, Java swing - java

I want my dissimilar-height panels to be top-aligned within their containing panel.
I've tried BorderLayout with NORTH, I've tried panel.setAlignmentY(TOP_ALIGNMENT). No luck with any approach so far.
(To post, I'm being asked to give more description. The remaining text (other than code) is my attempt to satisfy that requirement.) You can see the small panels containing the "label x" names, each stacked vertically. I definitely want vertical stacking of components within the panels, and I definitely will have different-height panels; don't ask me to make the panels the same height--it's my art choice that their bottoms will not line up.
package view;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI2 extends JFrame {
private static final long serialVersionUID = 1L;
public GUI2() {
setTitle("Paddle Events");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocation(100, 100);
// nesting enables me to see the border of the panel
getContentPane().add(getMainPanel());
setVisible(true);
}
private Component getMainPanel() {
JPanel panel = new JPanel();
panel.add(getGreenPanel());
panel.add(getDarkGrayPanel());
return panel;
}
private JPanel getGreenPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.green));
panel.setPreferredSize(new Dimension(175, 100));
panel.add(getWrapperA());
panel.add(getWrapperB());
panel.add(getWrapperC());
return panel;
}
private JPanel getDarkGrayPanel() {
JPanel panel = new JPanel();
panel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
panel.setPreferredSize(new Dimension(150, 70));
panel.add(getWrapperA());
panel.add(getWrapperB());
panel.add(getWrapperC());
return panel;
}
private Component getWrapperA() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(new JLabel("label 1"));
panel.add(new JLabel("label 2"));
panel.add(new JLabel("label 3"));
return panel;
}
private Component getWrapperB() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setAlignmentY(TOP_ALIGNMENT); // pointless
panel.add(new JLabel("label 4"));
panel.add(new JLabel("label 5"));
return panel;
}
private Component getWrapperC() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(new JLabel("label 6"));
return panel;
}
public static void main(String[] args) {
new GUI2();
}
}

There might be a differnet way to achieve the same thing, but for me, use a GridBagLayout, see How to Use GridBagLayout for more details
import java.awt.Color;
import java.awt.Component;
import static java.awt.Component.TOP_ALIGNMENT;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public Main() {
setTitle("Paddle Events");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 200);
setLocation(100, 100);
// nesting enables me to see the border of the panel
getContentPane().add(getMainPanel());
setVisible(true);
}
private Component getMainPanel() {
JPanel panel = new JPanel();
panel.add(getGreenPanel());
panel.add(getDarkGrayPanel());
return panel;
}
private JPanel getGreenPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.anchor = gbc.PAGE_START;
gbc.insets = new Insets(4, 2, 4, 2);
panel.setBorder(BorderFactory.createLineBorder(Color.green));
panel.setPreferredSize(new Dimension(175, 100));
panel.add(getWrapperA(), gbc);
panel.add(getWrapperB(), gbc);
panel.add(getWrapperC(), gbc);
return panel;
}
private JPanel getDarkGrayPanel() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.weighty = 1;
gbc.anchor = gbc.PAGE_START;
gbc.insets = new Insets(4, 2, 4, 2);
panel.setBorder(BorderFactory.createLineBorder(Color.darkGray));
panel.setPreferredSize(new Dimension(150, 70));
panel.add(getWrapperA(), gbc);
panel.add(getWrapperB(), gbc);
panel.add(getWrapperC(), gbc);
return panel;
}
private Component getWrapperA() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.black));
panel.add(new JLabel("label 1"));
panel.add(new JLabel("label 2"));
panel.add(new JLabel("label 3"));
return panel;
}
private Component getWrapperB() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.blue));
panel.setAlignmentY(TOP_ALIGNMENT); // pointless
panel.add(new JLabel("label 4"));
panel.add(new JLabel("label 5"));
return panel;
}
private Component getWrapperC() {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.setBorder(BorderFactory.createLineBorder(Color.red));
panel.add(new JLabel("label 6"));
return panel;
}
public static void main(String[] args) {
new Main();
}
}

Related

GUI JPanel & frame layout

I want to ask some question about Java GUI, especially on JPanel syntax. I'm really confused how to configure the panel exactly, try to use BorderLayout, and GridLayout, but it still doesn't meet my requirement.
I want to make form like below:
Current Result:
From the image, I need to configure that 2 points
The padding / margin between Input Panel and the Button Panel
The Padding / margin between tablePanel and the inputPanel
Code
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
public class manageForm extends JFrame {
//Vector<String> header=new Vector<String>();
//Vector<Vector<String>>data=new Vector<Vector<String>>();
DefaultTableModel defaultTableModel;
JTable table;
JScrollPane scrollPane;
JLabel titleLabel=new JLabel("Manage Handphone");
JTable hpTable = new JTable();
JLabel idLabel = new JLabel("ID");
JLabel nameLabel = new JLabel("Name");
JLabel priceLabel = new JLabel("Price");
JLabel weightLabel = new JLabel("Weight");
JLabel cableLabel = new JLabel("Cable Length");
JLabel typeLabel = new JLabel("Type");
JTextField idtxt = new JTextField();
JTextField nametxt = new JTextField();
JTextField pricetxt = new JTextField();
JTextField weighttxt = new JTextField();
JTextField cabletxt = new JTextField();
JComboBox typeBox = new JComboBox();
JButton insertBtn = new JButton("INSERT");
JButton updateBtn = new JButton("UPDATE");
JButton deleteBtn = new JButton("DELETE");
JButton confirmBtn = new JButton("CONFIRM");
JButton cancelBtn = new JButton("CANCEL");
String header[] = {"ID","Name","Type","Price","Weight","Cable Length"};
String data[][] = {
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"},
{"2","Bose Quite","In-Ear","Price","Weight","Cable Length"}
};
public manageForm() {
JPanel headerPanel = new JPanel();
JPanel tablePanel = new JPanel();
tablePanel.setBorder(new EmptyBorder(0,0,0,0));
JPanel inputPanel = new JPanel(new GridLayout(6,2));
inputPanel.setBorder(new EmptyBorder(20,10,20,10));
//inputPanel.setBorder(new LineBorder(Color.black));
JPanel buttonPanel = new JPanel(new GridLayout(1,5));
buttonPanel.setBorder(new EmptyBorder(100,20,100,20));
JPanel footerPanel = new JPanel(new GridLayout (2,1,0,0));
headerPanel.add(titleLabel);
inputPanel.add(idLabel);
inputPanel.add(idtxt);
inputPanel.add(nameLabel);
inputPanel.add(nametxt);
inputPanel.add(priceLabel);
inputPanel.add(pricetxt);
inputPanel.add(weightLabel);
inputPanel.add(weighttxt);
inputPanel.add(cableLabel);
inputPanel.add(cabletxt);
inputPanel.add(typeLabel);
inputPanel.add(typeBox);
buttonPanel.add(confirmBtn);
buttonPanel.add(cancelBtn);
buttonPanel.add(insertBtn);
buttonPanel.add(updateBtn);
buttonPanel.add(deleteBtn);
footerPanel.add(inputPanel);
footerPanel.add(buttonPanel);
/*
JPanel panel0=new JPanel();
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
JPanel panel3=new JPanel();
JPanel panel4=new JPanel();
JPanel panel5=new JPanel();
JPanel panel6 = new JPanel();
JPanel panel7 = new JPanel();
JPanel panel8 = new JPanel();
panel1.setLayout(new GridLayout(1, 6));
panel2.setLayout(new GridLayout(1, 2));
panel2.add(idLabel);
panel2.add(idtxt);
panel3.setLayout(new GridLayout(1, 2));
panel3.add(nameLabel);
panel3.add(nametxt);
panel4.setLayout(new GridLayout(1, 2));
panel4.add(priceLabel);
panel4.add(pricetxt);
panel5.setLayout(new GridLayout(1, 2));
panel5.add(weightLabel);
panel5.add(weighttxt);
panel6.setLayout(new GridLayout(1, 2));
panel6.add(cableLabel);
panel6.add(cabletxt);
panel7.setLayout(new GridLayout(1, 2));
panel7.add(typeLabel);
panel7.add(typeBox);
panel8.setLayout(new GridLayout(1, 5));
mainPanel.add(panel0);
mainPanel.add(panel1);
mainPanel.add(panel2);
mainPanel.add(panel3);
mainPanel.add(panel4);
mainPanel.add(panel5);
mainPanel.add(panel6);
mainPanel.add(panel7);
mainPanel.add(panel8);
*/
/*
header.add("ID");
header.add("Name");
header.add("Type");
header.add("Price");
header.add("Weight");
header.add("Cable Length");
*/
defaultTableModel=new DefaultTableModel(data, header);
hpTable =new JTable(defaultTableModel);
scrollPane=new JScrollPane(hpTable);
// tablePanel.add(scrollPane);
setLayout(new BorderLayout(0,5));
setTitle("Manage Form");
setSize(800,600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
add(headerPanel,BorderLayout.NORTH);
add(scrollPane,BorderLayout.CENTER);
add(footerPanel,BorderLayout.SOUTH);
pack();
}
public static void main(String[] args) {
new manageForm();
}
}
How exactly to manage the panel layout to meet our requirement?
I have tried EmptyBorder, but the result, it's only making a big space between the other panel.
Use GridBagLayout it is a powerful and best fit to your requirement. It is arranges the components in a horizontal and vertical manner.
You can put component in a grid using cells and rows. As a example:
read more - GridBagLayout
Strongly disagree with the suggestion to use GridBagLayout. That layout is basically a punchline for any Swing programmer.
If you're going to be programming Swing, do yourself a huge favor and use MiGLayout. It's the layout manager that Swing should have built-in.

How to center JLabel in a panel with BoxLayout

I'm a newbie in Java programming and I got a question about BoxLayout. I can't get the JLabels centered in a panel with BoxLayout
What I want is to change from what I got now:
to this:
getting the labels being totally in the middle of the panel.
Here's my code:
import java.awt.Dimension;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test extends JFrame{
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
public Test(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initWidgets();
setVisible(true);
}
private void initWidgets(){
setPreferredSize(new Dimension(300, 300));
label1 = new JLabel("Label 1");
label2 = new JLabel("Label 2");
label3 = new JLabel("Label 3");
label4 = new JLabel("Label 4");
label5 = new JLabel("Label 5");
JPanel jpanel = new JPanel();
label1.setAlignmentX(CENTER_ALIGNMENT);
label2.setAlignmentX(CENTER_ALIGNMENT);
label3.setAlignmentX(CENTER_ALIGNMENT);
label4.setAlignmentX(CENTER_ALIGNMENT);
label5.setAlignmentX(CENTER_ALIGNMENT);
jpanel.setLayout(new BoxLayout(jpanel, BoxLayout.PAGE_AXIS));
jpanel.add(label1);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label2);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label3);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label4);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label5);
add(jpanel);
pack();
}
public static void main(String[] args) {
new Test();
}
}
To vertically center the components you need to add "glue" at the start and end:
jpanel.add(Box.createVerticalGlue());
jpanel.add(label1);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label2);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label3);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label4);
jpanel.add(Box.createRigidArea(new Dimension(0, 10)));
jpanel.add(label5);
jpanel.add(Box.createVerticalGlue());
Read the section from the Swing tutorial on How to Use BoxLayout for more information.
try adding this after setAlignmentX
label1.setHorizontalAlignment(SwingConstants.CENTER);
label2.setHorizontalAlignment(SwingConstants.CENTER);
label3.setHorizontalAlignment(SwingConstants.CENTER);
label4.setHorizontalAlignment(SwingConstants.CENTER);
label5.setHorizontalAlignment(SwingConstants.CENTER);
then add the labels at the panel like this:
jpanel.add(label1, BorderLayout.CENTER);
jpanel.add(label2, BorderLayout.CENTER);
jpanel.add(label3, BorderLayout.CENTER);
jpanel.add(label4, BorderLayout.CENTER);
jpanel.add(label5, BorderLayout.CENTER);

Issues setting the layout in JFrame

i am trying to set the text box and label in panel but the text box is getting inappropriate size and the layout is also not setting properly
public class FrameLayout1 implements ActionListener {
JTextField[] txtName;
JLabel[] lblname;
JCheckBox keyButton;
JCheckBox cascadeButton;
JComboBox SetList;
JComboBox ClassList;
JLabel[] lblType;
JTextField txtJoinColumn;
JLabel[] lblAssoType;
JTextField[] txtJoinColumnAssoc;
FrameLayout1(){
}
public void setDetailsPanel()
{
txtName = new JTextField[10];
txtJoinColumnAssoc = new JTextField[10];
lblname=new JLabel[10];
lblType=new JLabel[10];
lblAssoType=new JLabel[20];
JFrame ColumnFrame=new JFrame("Enter the Column Values");
int i=0;
JPanel panel = new JPanel(new GridLayout(0,1,5,10));
for (i=0;i<5;i++)
{
JPanel panelTxtLbl = new JPanel(new GridLayout(0,2));
lblname[i] = new JLabel("label"+i+":", JLabel.LEFT);
panelTxtLbl.add(lblname[i]);
txtName[i] = new JTextField(15);
panelTxtLbl.add(txtName[i]);
panel.add(panelTxtLbl);
lblType[i] = new JLabel("labeldata", JLabel.LEFT);
panel.add(lblType[i]);
String[] SetStrings = { "One to Many","Many to Many" };
SetList = new JComboBox(SetStrings);
SetList.setSelectedIndex(1);
panel.add(SetList);
cascadeButton = new JCheckBox("cascade");
cascadeButton.setSelected(true);
panel.add(cascadeButton);
JPanel panelSetClass = new JPanel(new GridLayout(0,2));
for(int j=0;j<3;j++)
{
lblAssoType[j]=new JLabel("Label Inner"+j+":", JLabel.LEFT);
panelSetClass.add(lblAssoType[j]);
txtJoinColumnAssoc[j] = new JTextField(15);
panelSetClass.add(txtJoinColumnAssoc[j]);
}
panel.add(panelSetClass);
panel.add(createHorizontalSeparator());
}
//detailsPanel.add(panel, BorderLayout.CENTER);
//detailsPanel.setAutoscrolls(true);
panel.setAutoscrolls(true);
JButton button = new JButton("Submit");
button.addActionListener(this);
//detailsPanel.add(button,BorderLayout.PAGE_END);
panel.add(button,BorderLayout.PAGE_END);
Color c=new Color(205, 222, 216);
ColumnFrame.setLayout(new BorderLayout());
ColumnFrame.add(panel,BorderLayout.CENTER);
//ColumnFrame.setSize(700,600);
ColumnFrame.setBackground(c);
ColumnFrame.pack();
ColumnFrame.setVisible(true);
ColumnFrame.setLocation(200, 200);
}
/*
* to add a horizontal line in the panel
*/
static JComponent createHorizontalSeparator() {
JSeparator x = new JSeparator(SwingConstants.HORIZONTAL);
x.setPreferredSize(new Dimension(3,2));
return x;
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
createHorizontalSeparator function helps you add a horizontal line in the panel, as i was unable to segregate the fields .
current output
desired output
Today, I answered a similar question where GridLayout caused much the same
confusion. Do yourself a service and use a flexible layout manager
(if it is possible) like MigLayout to create your layouts. These
simple built-in layout managers either have very limited application
(GridLayout, FlowLayout, BorderLayout) or it can become challenging
to create sofisticated layouts with them (BoxLayout).
GridLayout and BorderLayout stretch their components and do not
honour the size bounds of their children. This is the reason why you
have those unnecessary spaces and why the button is expanded horizontally.
The following is an example that mimics your layout. It is created with
the powerful MigLayout manager.
package com.zetcode;
import java.awt.EventQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
public class DetailsPanel extends JFrame {
public DetailsPanel() {
initUI();
setTitle("Details");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
private void initUI() {
setLayout(new MigLayout("ins 10, wrap 2", "[][grow]"));
add(new JLabel("Label 1:"));
add(new JTextField(), "w 200, growx");
add(new JLabel("Label 2:"));
add(new JTextField(), "growx");
add(new JLabel("Label 3:"));
add(new JTextField(), "gaptop 30, growx");
add(new JLabel("Label 4:"));
add(new JTextField(), "growx");
add(new JLabel("Label 5:"));
add(new JTextField(), "gaptop 30, growx");
add(new JLabel("Label 6:"));
add(new JTextField(), "growx");
add(new JButton("Submit"), "gaptop 30, skip, right");
pack();
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
DetailsPanel ex = new DetailsPanel();
ex.setVisible(true);
}
});
}
}
You need to dedicate some time to learn a more complex layout manager, but
it pays off. Especially, if you often build layouts in Swing.

How to resize a JPanel to fit a JFrame in "docknorth" with no interference to remaining JPanels

I am doing a little test of a demo Swing GUI. In this demo, the JFrame is composed of 3 "master" JPanels. If you will, the first (jp1) is composed of JLabels, and the other two are composed of several other JPanels. I am using MigLayout.
Here is my sample code:
// All the jPanels
JFrame frame = new JFrame();
frame.setLayout(new MigLayout());
JPanel jp1 = new JPanel();
jp1.setLayout(new MigLayout());
jp1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp2 = new JPanel();
jp2.setLayout(new MigLayout());
jp2.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp3 = new JPanel();
jp3.setLayout(new MigLayout());
jp3.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp4 = new JPanel();
jp4.setLayout(new MigLayout());
jp4.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp5 = new JPanel();
jp5.setLayout(new MigLayout());
jp5.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp6 = new JPanel();
jp6.setLayout(new MigLayout());
jp6.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel jp7 = new JPanel();
jp7.setLayout(new MigLayout());
jp7.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel bigPanel1 = new JPanel();
bigPanel1.setLayout(new MigLayout());
bigPanel1.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
JPanel bigPanel2 = new JPanel();
bigPanel2.setLayout(new MigLayout());
bigPanel2.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
//All the labels to be added to JPanel jp1
JLabel label1 = new JLabel();
label1.setText("LABEL1");
JLabel label2 = new JLabel();
label2.setText("LABEL2");
JLabel label3 = new JLabel();
label3.setText("LABEL3");
JLabel label4 = new JLabel();
label4.setText("LABEL4");
jp1.add(label1);
jp1.add(label2);
jp1.add(label3);
jp1.add(label4,"wrap");
bigPanel1.add(jp2);
bigPanel1.add(jp6);
bigPanel1.add(jp3,"grow,wrap");
bigPanel2.add(jp4);
bigPanel2.add(jp7);
bigPanel2.add(jp5,"grow,wrap");
frame.getContentPane().add(jp1,"dock north, wrap");
frame.getContentPane().add(bigPanel1,"span,grow,wrap");
frame.getContentPane().add(bigPanel2,"span,grow,wrap");
frame.pack();
frame.setVisible(true);
Which results in this output:GUI OUTPUT
What I want to achieve is being able to add labels into the 1st JPanel (jp1) without messing with the remainder JPanels width.
Additionally, I want to make the several JPanels inside a bigPanel to occupy its full width, as well as in jp2,jp6 and jp3 to fill bigPanel1.
How should I do this? Thanks in advance.
I have never used MigLayout, and personally dont see the reason if it can be done using default java LayoutManager.
Okay so I used a combination FlowLayout and GridBagLayout to achieve this, along with gc.fill=GridBagConstraints.NONE and gc.anchor=GridBagConstraints.WEST for those panels which we dont want to fill the contentpane width, also updated as per your comment to stop the JPanel/JFrame from growing larger than the given max width when more JLabels are added this was done using a JScrollPane:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class Test {
public Test() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new GridBagLayout());
final JPanel labelPanel = new JPanel();
labelPanel.setBorder(new LineBorder(Color.black));
for (int i = 0; i < 5; i++) {
labelPanel.add(new JLabel("Label" + (i + 1)));
}
final int maxWidth = 200;
final JScrollPane jsp = new JScrollPane(labelPanel) {
#Override
public Dimension getPreferredSize() {
//we set the height by checking if we exceeed the wanted ith thus a scrollbar will appear an we must incoprate that or labels wont be shpwn nicely
return new Dimension(maxWidth, labelPanel.getPreferredSize().width < maxWidth ? (labelPanel.getPreferredSize().height + 5) : ((labelPanel.getPreferredSize().height + getHorizontalScrollBar().getPreferredSize().height) + 5));
}
};
JPanel otherPanel = new JPanel();
otherPanel.add(new JLabel("label"));
otherPanel.setBorder(new LineBorder(Color.black));
JPanel otherPanel2 = new JPanel();
otherPanel2.add(new JLabel("label 1"));
otherPanel2.add(new JLabel("label 2"));
otherPanel2.setBorder(new LineBorder(Color.black));
GridBagConstraints gc = new GridBagConstraints();
gc.fill = GridBagConstraints.BOTH;
gc.weightx = 1.0;
gc.weighty = 1.0;
gc.gridx = 0;
gc.gridy = 0;
frame.add(jsp, gc);
gc.fill = GridBagConstraints.NONE;
gc.anchor = GridBagConstraints.WEST;
gc.gridy = 1;
frame.add(otherPanel, gc);
gc.anchor = GridBagConstraints.WEST;
gc.gridy = 2;
frame.add(otherPanel2, gc);
frame.pack();
frame.setVisible(true);
frame.revalidate();
frame.repaint();
}
public static void main(String[] args) {
//Create Swing components on EDT
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Test();
}
});
}
}
I have use BorderLayout and FlowLayout to manage the layouts. The frame has two JPanel's and one JPanel in it has two more JPanel's. All the internal panels use FlowLayout to align the JLabels. To arrange these panels on the JFrame I have used BorderLayout.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;
public class LayoutTest {
public LayoutTest() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setLayout(new GridBagLayout());
JPanel motherPanel = new JPanel(new BorderLayout());
JPanel topPanel = new JPanel(new BorderLayout());
JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
motherPanel.add(topPanel, BorderLayout.NORTH);
motherPanel.add(bottomPanel, BorderLayout.CENTER);
JPanel topUpperPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
JPanel topBottomPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
topUpperPanel.setBorder(new LineBorder(Color.BLACK));
topBottomPanel.setBorder(new LineBorder(Color.BLACK));
bottomPanel.setBorder(new LineBorder(Color.BLACK));
topPanel.add(topUpperPanel, BorderLayout.PAGE_START);
topPanel.add(topBottomPanel, BorderLayout.CENTER);
for(int i = 0; i < 3; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
topUpperPanel.add(label);
}
for(int i = 0; i < 2; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
topBottomPanel.add(label);
}
for(int i = 0; i < 5; i++) {
JLabel label = new JLabel("Label-" + String.valueOf(i));
label.setBorder(new LineBorder(Color.BLACK));
bottomPanel.add(label);
}
frame.add(motherPanel);
frame.setTitle("Layout Manager");
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new LayoutTest();
}
});
}
}
P.S: I would suggest you to separate the panels such that there will be "whithout no interference with remaining JPanels."

Java: vertical alignment within JPanel

I am trying to vertically align (center) both JLabels inside one JPanel.
JPanel panel = new JPanel();
panel.setPreferredSize(size);
JLabel label1 = new JLabel(icon);
JLabel label2 = new JLabel("text");
panel.add(label1);
panel.add(label2);
I have tried using setAligmentY() with no success. Both labels always appear on the top of JPanel.
UPD: Labels should be located next to each other like using FlowLayout, but in the middle of the JPanel.
Use a GridBagLayout with the default constraints. Here is a small demo code:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestVerticalAlignement {
protected void initUI() {
final JFrame frame = new JFrame();
frame.setTitle("Test vertical alignement");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JLabel label1 = new JLabel("label1");
JLabel label2 = new JLabel("label2");
panel.add(label1, gbc);
panel.add(label2, gbc);
frame.add(panel);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestVerticalAlignement().initUI();
}
});
}
}
you can see this answer:
https://stackoverflow.com/a/18073909/189411
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
Use gridlayout, simple.
That should work.
Consider my following example:
import java.awt.*;
import java.applet.Applet;
import javax.swing.*;
/*
<applet code=AJ07 width=450 height=450>
</applet>
*/
public class AJ07 extends JApplet{
Container c=null;
public void init(){
JPanel pTop=new JPanel();
JPanel pLeft=new JPanel();
JPanel pCenter=new JPanel();
JPanel pProperties=new JPanel();
pLeft.setLayout(new GridLayout(20,1));
c=this.getContentPane();
JButton bNew=new JButton("New");
pTop.add(bNew);
JButton bOpen=new JButton("Open");
pTop.add(bOpen);
JButton bSave=new JButton("Save");
pTop.add(bSave);
JButton bSaveAll=new JButton("Save All");
pTop.add(bSaveAll);
JButton bRun=new JButton("Run");
pTop.add(bRun);
JButton bStop=new JButton("Stop");
pTop.add(bStop);
JButton bPause=new JButton("Pause");
pTop.add(bPause);
JButton bText=new JButton("TextBox");
pLeft.add(bText);
JButton bButton=new JButton("Button");
pLeft.add(bButton);
pProperties.setLayout(new GridLayout(20,1));
pProperties.add(new Label("BackColor"));
pProperties.add(new Label("ForeColor"));
c.add(new TextArea(),BorderLayout.CENTER);
c.add(pTop,BorderLayout.NORTH);
c.add(pLeft,BorderLayout.WEST);
c.add(new Label("Project Loaded Successfully!"),BorderLayout.SOUTH);
c.add(pProperties,BorderLayout.EAST);
//c.add(pCenter,BorderLayout.CENTER);
}
}
for which the output is as follows:

Categories