How to center JLabel in a panel with BoxLayout - java

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

Related

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

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

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.

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:

Set button size smaller in Java Swing

I am trying to implement a GUI in Java Swing; but I am stuck on the button size, which I am trying to make smaller. I have tried to use setSize, setPrefferedSize and setmaximumSize, but nothing worked. Any ideas?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.*;
import javax.swing.border.Border;
public class WorkStationGUI extends JFrame implements ActionListener {
JButton Worker1Process1;
JButton Worker1Process2;
JButton StopWorking;
// JScrollPane scrollList;
JTextArea OrderList;
JTextArea ProductList;
JTextField orders;
JTextField products;
JTextField Worker1;
JTextField Worker2;
private HashMap<String, Order> OrdersList;
private HashMap<String, Product> ProductsList;
public WorkStationGUI(HashMap<String, Order> orders, HashMap<String, Product> Products) {
this.OrdersList = orders;
this.ProductsList = Products;
setTitle("Work Station");
setupEastandWest();
setupSouthPanel();
pack();
setVisible(true);
}
private JLabel createOneLabel(String s, Color c) {
Font f = new Font(Font.SANS_SERIF, Font.BOLD, 18);
JLabel label = new JLabel(s, JLabel.CENTER);
label.setFont(f);
label.setBackground(c);
label.setOpaque(true);
return label;
}
private void setupEastandWest() {
// search panel contains label, text field and button
JPanel Panel = new JPanel();
Worker1Process1 = new JButton("Worker 1");
Worker1Process1.setPreferredSize(new Dimension(10, 10));
Panel.add(Worker1Process1);
Worker1 = new JTextField(20);
Worker1Process1.setPreferredSize(new Dimension(90, 90));
Worker1.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
Worker1.setEditable(false);
Panel.setLayout(new GridLayout(2, 1));
Panel.add(Worker1);
JPanel Panel2 = new JPanel();
Worker1Process2 = new JButton("Worker 2");
Panel2.add(Worker1Process2);
Worker2 = new JTextField(20);
Worker2.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 14));
Worker2.setEditable(false);
Panel2.setLayout(new GridLayout(2, 1));
Panel2.add(Worker2);
Panel.setLayout(new GridLayout(2, 2));
this.add(Panel, BorderLayout.EAST);
this.add(Panel2, BorderLayout.WEST);
// this.add(Panel2, BorderLayout.SOUTH);
}
private void setupSouthPanel() {
JPanel Panel = new JPanel();
orders = new JTextField(1);
orders.setBackground(Color.LIGHT_GRAY);
Panel.add(orders);
JPanel Panel2 = new JPanel();
products = new JTextField(1);
Panel.add(products);
products.setBackground(Color.LIGHT_GRAY);
Panel.setLayout(new GridLayout(2, 2));
this.add(Panel, BorderLayout.CENTER);
this.add(Panel2, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
}
}
You are using GridLayout which will cause the component to take up all container space, relative to the grid. It's not really the best choice for buttons. You might try using a FlowLayout, or GridBagLayout instead.
Also, you are setting the layout manager AFTER you are setting the JButton on the panel.

How to draw a separator across a panel using MigLayout

This is a MigLayout-newbie question. I'd like to know how to draw a separator from the end of a label across the width of a panel.
Here's my example code:
package com.ndh.swingjunk;
import java.awt.*;
import javax.swing.*;
import net.miginfocom.swing.MigLayout;
class MyJFrame extends JFrame {
public MyJFrame() {
super();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("foo");
label.setFont(new Font("Tahoma", Font.BOLD, 11));
JSeparator separator = new JSeparator();
JLabel anotherLabel = new JLabel("some other label");
anotherLabel.setFont(new Font("Tahoma", Font.PLAIN, 11));
JButton button1 = new JButton("button 1");
JButton button2 = new JButton("button 2");
JPanel panel = new JPanel(new MigLayout());
panel.add(label);
panel.add(separator, "growx, wrap");
panel.add(anotherLabel);
panel.add(button1);
panel.add(button2);
getContentPane().add(panel);
pack();
}
}
public class SeparatorLayoutQuestion {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override public void run() {new MyJFrame().setVisible(true);}});}}
and here's the result:
which is terribly lame. I'd like the separator to stretch from the end of "Foo" to the end of the panel, all the way across button 2.
Here's what worked for me, I had to use "split" so the label and separator could share the same cell:
JPanel panel = new JPanel(new MigLayout());
panel.add(label, "split 2, span");
panel.add(separator, "growx, wrap");
panel.add(anotherLabel);
panel.add(button1);
panel.add(button2);
try adding
"span 3"
to the first label

Categories