GUI JPanel & frame layout - java

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.

Related

COMPOUND BORDER : Get a outline border with title outside the Jpanel in java Swing

My only problem is that I don't know how to put my border outside the panel. I've tried compound and some other border code but so far I am unable to put it outside. It either disappears or it doesn't change at all.
The output that I want:
The output that I'm getting :
I'm a newbie at swing and I have been searching and found out about compound border but I am still not so familiar on how it works with adding the buttons into the panel. (I've removed the code of me trying to do compound border because it was just a mess full of errors)
THE CODE :
package activityswing;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.Border;
public class swing {
public static void main (String args []) {
JFrame pa= new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
//label
JLabel lb1= new JLabel("Panel 1");
JLabel lb2= new JLabel("Panel 2");
//adding label to panel
lb1.add(panel1);
lb1.add(panel2);
//panel1
Border line1 = BorderFactory.createLineBorder(Color.blue);
panel1.setBorder(line1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
panel1.setBackground(Color.BLUE);
panel1.setPreferredSize(new Dimension(270,40));
//panel2
Font font2 = new Font("Verdana",Font.ITALIC,12);
Border line2 = BorderFactory.createLineBorder(Color.blue);
lb2.setFont(font2);
panel2.setBorder(line2);
LayoutManager layout = new FlowLayout();
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.add(lb2);
panel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
panel2.setBackground(Color.GREEN);
panel2.setPreferredSize(new Dimension(270,40));
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50,50);
pa.setLayout(flow);
pa.pack();
pa.add(panel1);
pa.add(panel2);
pa.setSize(700,200);
pa.setResizable(false);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
Don't add component to labels
lb1.add(panel1);
lb1.add(panel2);
Labels calculate their preferred size based the label properties (text/icon/font/etc) and not the child components.
Don't mess with the preferredSize of the components unless you are absolutely certain you willing to take over all the responsibility to calculate the components size.
The simple solution would be to create a instance of TitledBorder yourself, for example...
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border = new TitledBorder("Panel 1");
border.setTitleFont(font2);
I'd kind of tempted to create a factory method to make this easier, but you get the general idea
To get the border "separated" from the component, I would use a compound component approach, where the outer panel contains the title and then add the inner panel into it.
If needed, you could use CompoundBorder and use a EmptyBorder on the side of the outer panel
Have a look at:
JavaDocs for TitledBorder
How to Use Borders
... for more details
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.LayoutManager;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.TitledBorder;
public class Test {
public static void main(String args[]) {
JFrame pa = new JFrame("Swing Activity");
//boarder
pa.setLayout(new BorderLayout());
//panels
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
//buttons
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
JButton button3 = new JButton("Button 3");
JButton button4 = new JButton("Button 4");
JButton button5 = new JButton("Button 5");
JButton button6 = new JButton("Button 6");
Font font2 = new Font("Verdana", Font.ITALIC, 12);
TitledBorder border1 = new TitledBorder("Panel 1");
border1.setTitleFont(font2);
JPanel outter1 = new JPanel(new BorderLayout());
outter1.setBorder(border1);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.setBackground(Color.BLUE);
outter1.add(panel1);
//panel2
LayoutManager layout = new FlowLayout();
TitledBorder border2 = new TitledBorder("Panel 2");
JPanel outter2 = new JPanel(new BorderLayout());
outter2.setBorder(border2);
panel2.setLayout(layout);
panel2.add(button4);
panel2.add(button5);
panel2.add(button6);
panel2.setBackground(Color.GREEN);
outter2.add(panel2);
//FRAME
FlowLayout flow = new FlowLayout(FlowLayout.CENTER, 50, 50);
pa.setLayout(flow);
pa.add(outter1);
pa.add(outter2);
pa.pack();
pa.setLocationRelativeTo(null);
pa.setVisible(true);
pa.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pa.setLocationRelativeTo(null);
}
}
You can nest JPanels. That is how I implemented the output you want.
The below code is not a correction of your code, it is an example of how to achieve the output you want. Since the two JPanels in your code are quite similar, the below code only displays a single JPanel. I assume you can make the appropriate changes.
package activityswing;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.CompoundBorder;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class Swing2 {
private JPanel createInner() {
JPanel inner = new JPanel();
inner.setBackground(Color.GREEN);
JButton button1 = new JButton("Button 1");
inner.add(button1);
JButton button2 = new JButton("Button 2");
inner.add(button2);
JButton button3 = new JButton("Button 3");
inner.add(button3);
return inner;
}
private JPanel createOuter() {
JPanel outer = new JPanel();
TitledBorder titledBorder = new TitledBorder(new LineBorder(Color.blue), "Panel 1");
Font font2 = new Font("Verdana", Font.BOLD + Font.ITALIC, 12);
titledBorder.setTitleFont(font2);
EmptyBorder emptyBorder = new EmptyBorder(10, 10, 10, 10);
CompoundBorder compoundBorder = new CompoundBorder(titledBorder, emptyBorder);
outer.setBorder(compoundBorder);
outer.add(createInner());
return outer;
}
private void showGui() {
JFrame frame = new JFrame("Swing2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createOuter());
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new Swing2().showGui());
}
}
Running the above code displays the following window.

Swing JButton is glitching with JCheckBox focus state

I have a JPanel set with the Windows Look and Feel. I have 3 JCheckBoxes, including 2 disabled ones which don't interfere with this problem. However, the non-disabled one is glitching with the JButton I have later in this JPanel:
The JCheckBox code:
JCheckBox checkBox = new JCheckBox("TTxJIRA Bash");
checkBox.setSize(300, (checkBox.getFontMetrics(checkBox.getFont()).getHeight()));
checkBox.setLocation(10, 100);
checkBox.setVisible(true);
checkBox.setSelected(true);
checkBox.setBackground(new Color(0, 0, 0, 0));
checkBox.setFocusable(false);
add(checkBox);
And the JButton code:
JButton button = new JButton("Install");
button.setSize(80, 25);
button.setLocation(getWidth() - 100, getHeight() - 60);
button.setFocusable(false);
button.setVisible(true);
add(button);
When I hover on the button, then hover on the checkbox, this glitch occurs:
My wild guess makes me think this has to do with two components being focused at the same time, but adding the button.setFocusable(false); did not help.
Here's a little runnable example that shows you how you could use LayoutManagers for that, because LayoutManagers will fix your problems you had with absolute positioning. (Please note that this is probably not the best solution and that the LineBorders are just for visualization)
Kinda messy code:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.LineBorder;
public class LayoutManagerExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JButton button = new JButton("Install");
JCheckBox cb1 = new JCheckBox("1");
cb1.setEnabled(false);
JCheckBox cb2 = new JCheckBox("2");
cb2.setEnabled(false);
JCheckBox cb3 = new JCheckBox("3");
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10,10,10,10);
JPanel southPanel = new JPanel();
southPanel.setLayout(new BorderLayout());
southPanel.setBorder(new LineBorder(Color.BLACK));
JPanel westPanel = new JPanel();
westPanel.setLayout(new GridLayout(10,1));
westPanel.setBorder(new LineBorder(Color.BLACK));
JPanel southEastPanel = new JPanel();
southEastPanel.setBorder(new LineBorder(Color.BLACK));
mainPanel.add(southPanel,BorderLayout.SOUTH);
mainPanel.add(westPanel,BorderLayout.WEST);
southPanel.add(southEastPanel,BorderLayout.EAST);
westPanel.add(cb1);
westPanel.add(cb2);
westPanel.add(cb3);
southEastPanel.add(button, gbc);
frame.add(mainPanel);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}

Adding a JTextArea to a TabbedPane

I am trying to get my JTextArea to display under all other contents of the llpPanel. My code is below with a screenshot of what my code displays. In the code you will see that I have set my dimensions for the JTextArea to (50, 50). Then in the llpPanel I have added BorderLayout.PAGE_END. I have also tried to (instead of PAGE_END) put CENTER and SOUTH. When I put SOUTH, it shows a white line at the very bottom of the program but you cannot do anything with it.
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JTextArea logbox = new JTextArea(50, 50);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.add(online);
llpPanel.add(offline);
llpPanel.add(status);
llpPanel.add(reboot);
llpPanel.add(account);
llpPanel.add(amount);
llpPanel.add(reset);
llpPanel.add(approvordecl);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
Updated code with screenshot is below...
import java.awt.BorderLayout;
import java.awt.ComponentOrientation;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class TestApplication implements ActionListener {
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setSize(1000, 1000);
frame.setTitle("RBA Test Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
JTextArea logbox = new JTextArea(50, 50);
JButton initialize = new JButton("Initialize");
JButton connect = new JButton("Connect");
JButton disconnect = new JButton("Disconnect");
JButton shutdown = new JButton("Shut Down");
JButton portsettings = new JButton("Port Settings");
JButton online = new JButton("Go Online");
JButton offline = new JButton("Go Offline");
JButton status = new JButton("Status");
JButton reboot = new JButton("Reboot");
JButton account = new JButton("Account");
JButton amount = new JButton("Amount");
JButton reset = new JButton("Reset");
JButton approvordecl = new JButton("Approve / Decline");
JButton test = new JButton("Test Button #1");
JButton testing = new JButton("Test Button #2");
JRadioButton button = new JRadioButton("Radio Button");
JRadioButton button2 = new JRadioButton("Radio Button");
JCheckBox checkbox = new JCheckBox("Check Box");
JCheckBox checkbox2 = new JCheckBox("Check Box");
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
newButtonPanel.add(offline);
newButtonPanel.add(status);
newButtonPanel.add(reboot);
newButtonPanel.add(account);
newButtonPanel.add(amount);
newButtonPanel.add(reset);
newButtonPanel.add(approvordecl);
JPanel testPanel = new JPanel();
testPanel.add(button);
testPanel.add(button2);
testPanel.add(checkbox2);
JPanel posPanel = new JPanel();
posPanel.add(test);
posPanel.add(testing);
posPanel.add(checkbox);
JPanel llpPanel = new JPanel();
llpPanel.setLayout(new BorderLayout());
llpPanel.add(newButtonPanel);
llpPanel.add(logbox, BorderLayout.PAGE_END);
JPanel buttonPanel = new JPanel();
buttonPanel.add(initialize);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
buttonPanel.add(shutdown);
buttonPanel.add(portsettings);
frame.add(buttonPanel);
frame.add(buttonPanel, BorderLayout.NORTH);
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("LLP", null, llpPanel, "Low Level Protocol");
tabbedPane.addTab("POS",null, posPanel, "Point Of Sale");
tabbedPane.addTab("Test", null, testPanel, "Test");
JPanel tabsPanel = new JPanel(new BorderLayout());
tabsPanel.add(tabbedPane);
frame.add(tabsPanel, BorderLayout.CENTER);
frame.pack();
}
#Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
}
}
JPanels use FlowLayout by default so applying BorderLayout constraints such as PAGE_END will have no effect. You need to set the layout of the panel:
llpPanel.setLayout(new BorderLayout());
Then you will encounter the problem of components displacing themselves in the BorderLayout.CENTER position. The solution is to create another JPanel as a container for the components other than logbox on llpPanel.
JPanel newButtonPanel = new JPanel();
newButtonPanel.add(online);
...
llpPanel.add(newButtonPanel);
JScrollPane scrollPane = new JScrollPane(logbox) {
#Override
public java.awt.Dimension getPreferredSize() {
return new Dimension(500, 500);
};
};
llpPanel.add(scrollPane, BorderLayout.PAGE_END);
Use a JScrollPane rather than adding the JTextArea directly to the container.
Set the component's preferred size property rather than its size, and add it to BorderLayout.SOUTH. For BorderLayout layouts, the container will try to use preferred sizes for the edges (north,south,east and west) and resize the center accordingly.
A short snipped example to illustrate. The view is a panel, which will have the text area at the bottom that is 50 high. This is done by adding the JTextArea component at BorderLayout.SOUTH and set the preferred size property at Dimension(0,50). The rest of the view is filled with a panel. This panel is placed at the BorderLayout.CENTER and will be resized by the layout manager.
JPanel view = new JPanel( );
view.setSize( 800, 600 );
view.setLayout( new BorderLayout( ) );
JPanel topArea = new JPanel( );
JTextArea textArea = new JTextArea( );
textArea.setPreferredSize( new Dimension( 0, 50 ) );
view.add( topArea, BorderLayout.CENTER );
view.add( textArea, BorderLayout.SOUTH );

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.

Categories