GUI Layout with swing components JAVA - java

This is what i want to achieve
I used grid layout and this is what have
and my code goes (not full code can provide one if needed).
components.setLayout(new GridLayout(4,0));
components.setBorder(BorderFactory.createTitledBorder("Personal Data"));
//Lable to display
name.setText("Resident Name");
roomNo.setText("Room Number");
age.setText("Age");
gender.setText("Gender");
careLvl.setText("Care Level");
components.add(name);
components.add(textFieldForName);
components.add(roomNo);
components.add(textFieldForAge);
components.add(age);
components.add(coForAge);
components.add(gender);
components.add(coForGender);
components.add(careLvl);
components.add(coForCareLvl);
any heads up would be greatly appreciated.

GridLayout does just that, it layouts components out in a grid, where each cell is percentage of the available space based on the requirements (ie width / columns and height / rows).
Take a look at A Visual Guide to Layout Managers for examples of the basic layout managers and what they do.
I would recommend that you take a look at GridBagLayout instead. It is the most flexible (and most complex) layout manager available in the default libraries.
For Example
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout31 {
public static void main(String[] args) {
new TestLayout31();
}
public TestLayout31() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JLabel lblRes = new JLabel("Resident Name");
JLabel lblRoomNo = new JLabel("RoomNo");
JLabel lblAge = new JLabel("Age");
JLabel lblGender = new JLabel("Gender");
JLabel lblCare = new JLabel("Care level");
JTextField fldRes = new JTextField("john smith", 20);
JTextField fldRoomNo = new JTextField(10);
JComboBox cmbAge = new JComboBox(new Object[]{51});
JComboBox cmbGener = new JComboBox(new Object[]{"M", "F"});
JComboBox cmbCare = new JComboBox(new Object[]{"Low"});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(1, 1, 1, 1);
add(lblRes, gbc);
gbc.gridx++;
gbc.gridwidth = 4;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(fldRes, gbc);
gbc.gridx = 7;
gbc.gridwidth = 1;
gbc.fill = GridBagConstraints.NONE;
add(lblRoomNo, gbc);
gbc.gridx++;
add(fldRoomNo, gbc);
gbc.gridy++;
gbc.gridx = 1;
add(lblAge, gbc);
gbc.gridx++;
add(cmbAge, gbc);
gbc.gridx++;
add(lblGender, gbc);
gbc.gridx++;
add(cmbGener, gbc);
gbc.gridx++;
gbc.gridwidth = 2;
add(lblCare, gbc);
gbc.gridx += 2;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(cmbCare, gbc);
}
}
}
Compound Layout Example
Another option would be to use a compound layout. This is, you separate each section of your UI into separate containers, concentrating on their individual layout requirements.
For example, you have two rows of fields, each which don't really relate to each other, so rather than trying to figure out how to make the fields line up, you can focus on each row separately...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestLayout31 {
public static void main(String[] args) {
new TestLayout31();
}
public TestLayout31() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
JPanel topPane = new JPanel(new GridBagLayout());
JLabel lblRes = new JLabel("Resident Name");
JLabel lblRoomNo = new JLabel("RoomNo");
JLabel lblAge = new JLabel("Age");
JLabel lblGender = new JLabel("Gender");
JLabel lblCare = new JLabel("Care level");
JTextField fldRes = new JTextField("john smith", 20);
JTextField fldRoomNo = new JTextField(10);
JComboBox cmbAge = new JComboBox(new Object[]{51});
JComboBox cmbGener = new JComboBox(new Object[]{"M", "F"});
JComboBox cmbCare = new JComboBox(new Object[]{"Low"});
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(1, 1, 1, 1);
topPane.add(lblRes, gbc);
gbc.gridx++;
gbc.fill = GridBagConstraints.HORIZONTAL;
topPane.add(fldRes, gbc);
gbc.gridx++;
topPane.add(lblRoomNo, gbc);
gbc.gridx++;
topPane.add(fldRoomNo, gbc);
JPanel bottomPane = new JPanel(new GridBagLayout());
gbc.gridx = 0;
bottomPane.add(lblAge, gbc);
gbc.gridx++;
bottomPane.add(cmbAge, gbc);
gbc.gridx++;
bottomPane.add(lblGender, gbc);
gbc.gridx++;
bottomPane.add(cmbGener, gbc);
gbc.gridx++;
bottomPane.add(lblCare, gbc);
gbc.gridx++;
bottomPane.add(cmbCare, gbc);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(topPane, gbc);
gbc.gridy++;
add(bottomPane, gbc);
}
}
}
This will make it easier to modify the UI later should you have to...

JFrame frame = new JFrame();
JPanel contentPane = new JPanel();
JPanel northPane = new JPanel();
JPanel centerPane = new JPanel();
JPanel southPane = new JPanel();
contentPane.setLayout(new BorderLayout());
northPane.setLayout( new GridLayout(1, 6));
southPane.setLayout( new GridLayout(1, 7));
contentPane.add(northPane, BorderLayout.NORTH );
contentPane.add(centerPane, BorderLayout.CENTER);
contentPane.add(southPane, BorderLayout.SOUTH );
frame.setContentPane(contentPane);
JLabel residentNameLabel = new JLabel("Resident name ");
JTextField residentNameText = new JTextField();
JLabel roomNoLabel = new JLabel("RoomNo ");
JTextField roomNoText = new JTextField();
JLabel emptyLabel0 = new JLabel(" ");
JLabel emptyLabel1 = new JLabel(" ");
JLabel emptyLabel2 = new JLabel(" ");
JLabel emptyLabel3 = new JLabel(" ");
JLabel ageLabel = new JLabel("Age ");
JComboBox<String> ageComboBox = new JComboBox<String>();
ageComboBox.addItem("50");
ageComboBox.addItem("51");
ageComboBox.addItem("52");
ageComboBox.addItem("53");
ageComboBox.addItem("54");
ageComboBox.addItem("55");
JLabel genderLabel = new JLabel("Gender ");
JComboBox<String> genderComboBox = new JComboBox<String>();
genderComboBox.addItem("M");
genderComboBox.addItem("F");
JLabel careLevelLabel = new JLabel("Care Level ");
JComboBox<String> careLevelComboBox = new JComboBox<String>();
genderComboBox.addItem("low");;
genderComboBox.addItem("medium");
genderComboBox.addItem("high");
residentNameLabel.setHorizontalAlignment(JLabel.RIGHT);
roomNoLabel.setHorizontalAlignment(JLabel.RIGHT);
ageLabel.setHorizontalAlignment(JLabel.RIGHT);
genderLabel.setHorizontalAlignment(JLabel.RIGHT);
careLevelLabel.setHorizontalAlignment(JLabel.RIGHT);
northPane.add(emptyLabel0 );
northPane.add(residentNameLabel);
northPane.add(residentNameText );
northPane.add(roomNoLabel );
northPane.add(roomNoText );
northPane.add(emptyLabel1 );
centerPane.add(emptyLabel2 );
southPane.add(ageLabel );
southPane.add(ageComboBox );
southPane.add(genderLabel );
southPane.add(genderComboBox );
southPane.add(careLevelLabel );
southPane.add(careLevelComboBox);
southPane.add(emptyLabel3 );
contentPane.setBorder(BorderFactory.createTitledBorder("Personal Data"));
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent evt) {
System.exit(0);
}
});
frame.setVisible(true);
frame.pack();

Related

How to improve the margin and padding of JPanel?

When I initially run my Java Swing application, the padding and margining of the JLabel and JTextField components in a JPanel look good. But whenever I resize the application, the padding and margining for the labels and text fields increases so much that it does not look as good.
I understand a GridLayout has a set amount of vertical and horizontal spacing, but what can I do to make the spacing look better as the size of the application increases? I would also like the text in the text fields to resize as the text field increases but have been unable to figure it out.
I have been thinking to use a GridBagLayout but have not had much luck with that either. There is just way too much spacing as the size increases, which does not look good, and I have been unable to find or learn a good solution.
I would appreciate any advice.
Code:
package TestPackage;
import java.awt.GridLayout;
import javax.swing.*;
public class TestGridLayout {
public static void main(String[] args) {
JPanel testPanel = new JPanel();
GridLayout layoutManager = new GridLayout(5,2);
testPanel.setLayout(layoutManager);
JLabel platformEnumerationNameLabel = new JLabel();
JLabel logicalEnumerationNameFieldLabel = new JLabel();
JLabel valueTypeUnitNameFieldLabel = new JLabel();
JLabel measurementNameFieldLabel = new JLabel();
JLabel measurementAxisNameFieldLabel = new JLabel();
JTextField platformEnumerationNameField = new JTextField();
JTextField logicalEnumerationNameField = new JTextField();
JTextField valueTypeUnitNameField = new JTextField();
JTextField measurementNameField = new JTextField();
JTextField measurementAxisNameField = new JTextField();
platformEnumerationNameLabel.setText("Label 1");
testPanel.add(platformEnumerationNameLabel);
platformEnumerationNameField.setText("input some data");
testPanel.add(platformEnumerationNameField);
logicalEnumerationNameFieldLabel.setText("Label 2");
testPanel.add(logicalEnumerationNameFieldLabel);
logicalEnumerationNameField.setText("input some data");
testPanel.add(logicalEnumerationNameField);
valueTypeUnitNameFieldLabel.setText("Label 3");
testPanel.add(valueTypeUnitNameFieldLabel);
valueTypeUnitNameField.setText("input some data");
testPanel.add(valueTypeUnitNameField);
measurementNameFieldLabel.setText("Label 4");
testPanel.add(measurementNameFieldLabel);
measurementNameField.setText("input some data");
testPanel.add(measurementNameField);
measurementAxisNameFieldLabel.setText("Label 5");
testPanel.add(measurementAxisNameFieldLabel);
measurementAxisNameField.setText("input some data");
testPanel.add(measurementAxisNameField);
JDialog dialog = new JDialog();
dialog.add(testPanel);
dialog.setSize(700,200);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
}
}
Use a different layout manager that doesn't resize all the components (unless you want them to)
See How to Use GridBagLayout for more details
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame frame = new JFrame();
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(8, 8, 8, 8);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel platformEnumerationNameLabel = new JLabel();
JLabel logicalEnumerationNameFieldLabel = new JLabel();
JLabel valueTypeUnitNameFieldLabel = new JLabel();
JLabel measurementNameFieldLabel = new JLabel();
JLabel measurementAxisNameFieldLabel = new JLabel();
JTextField platformEnumerationNameField = new JTextField(20);
JTextField logicalEnumerationNameField = new JTextField(20);
JTextField valueTypeUnitNameField = new JTextField(20);
JTextField measurementNameField = new JTextField(20);
JTextField measurementAxisNameField = new JTextField(20);
platformEnumerationNameLabel.setText("Label 1");
add(platformEnumerationNameLabel, gbc);
gbc.gridx++;
platformEnumerationNameField.setText("input some data");
add(platformEnumerationNameField, gbc);
gbc.gridy++;
gbc.gridx = 0;
logicalEnumerationNameFieldLabel.setText("Label 2");
add(logicalEnumerationNameFieldLabel, gbc);
gbc.gridx++;
logicalEnumerationNameField.setText("input some data");
add(logicalEnumerationNameField, gbc);
gbc.gridy++;
gbc.gridx = 0;
valueTypeUnitNameFieldLabel.setText("Label 3");
add(valueTypeUnitNameFieldLabel, gbc);
gbc.gridx++;
valueTypeUnitNameField.setText("input some data");
add(valueTypeUnitNameField, gbc);
gbc.gridy++;
gbc.gridx = 0;
measurementNameFieldLabel.setText("Label 4");
add(measurementNameFieldLabel, gbc);
gbc.gridx++;
measurementNameField.setText("input some data");
add(measurementNameField, gbc);
gbc.gridy++;
gbc.gridx = 0;
measurementAxisNameFieldLabel.setText("Label 5");
add(measurementAxisNameFieldLabel, gbc);
gbc.gridx++;
measurementAxisNameField.setText("input some data");
add(measurementAxisNameField, gbc);
}
}
}

how to design panel from tabbedpane and make panel to center

i want to make a bigger resolution/fullscreen but i dont know what layout should i use, can u guys help me to choose a better layout
this is the first code for first pic
tp = new JTabbedPane();
tp.setBounds(0,0,250,400);
panel = new JPanel();
panel.setPreferredSize(new Dimension(250, 480));
tp.addTab("Mahasiswa",panel);
panel.setLayout(new FlowLayout());
label_insert = new JLabel("NIM : ");
label_insert2 = new JLabel("ID Jurusan : ");
tf_insert1 = new JTextField(15);
tf_insert2 = new JTextField(15);
Insert = new JButton(" Insert ");
//panel add
this one i want to make it on middle of frame and all of them already on panel, how can i move it to the middle ?
this is code for the second picture
public void mainform(){
main = new JPanel();
main.setLayout(new FlowLayout(FlowLayout.CENTER));
label_main = new JLabel("ID");
label_main2 = new JLabel("Password");
tf_main = new JTextField(15);
tf_main2 = new JPasswordField(15);
login = new JButton("LOGIN");
login.addActionListener(this);
main.add(label_main);
main.add(tf_main);
main.add(label_main2);
Following this guide here I would suggest the following:
yourFrame = new JFrame();
yourFrame.setLayout(new BorderLayout());
tp = new JTabbedPane();
yourFrame.add(tp, BorderLayout.CENTER);
Then fiddle with GridLayout, GridBagLayout, or GroupLayout for the tabs in your tabbedpane.
I would consider using a GridBagLayout which will give you greater flexibility in how the components are laid out
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(2, 2, 2, 2);
add(new JLabel("ID"), gbc);
gbc.gridx++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
add(new JLabel("Password"), gbc);
gbc.gridx++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.CENTER;
add(new JButton("Login"), gbc);
}
}
}
See Laying Out Components Within a Container and How to Use GridBagLayout for more details

Bottom of JScrollPane is cut off

I am trying to create a simple email client and the bottom of the body is being cut-off. If I add a horizontal scroll bar, it does not appear, and the bottom of the Vertical scroll bar does not appear either.
Here is my code:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
#SuppressWarnings("serial")
public class gui extends JFrame{
gui(String title, int x, int y){
super(title);
setSize(x,y);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
public void addElements(){
Font size30 = new Font(null, Font.PLAIN, 30);
JPanel pnl = new JPanel();
Container contentPane = getContentPane();
//--- User Info ---//
JPanel userInfo = new JPanel();
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel);
userInfo.add(userField);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
userInfo.add(passLabel);
userInfo.add(passField);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
userInfo.add(serverLabel);
userInfo.add(serverField);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
userInfo.add(portLabel);
userInfo.add(portField);
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel();
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel);
msgInfo.add(toField);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
msgInfo.add(subLabel);
msgInfo.add(subField);
//--- Body ---//
JPanel bodyPnl = new JPanel(new BorderLayout(10,10));
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30,70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bodyScroll.setBounds(getX(), getY(), bodyField.getWidth(), bodyField.getHeight());
bodyPnl.add("South",bodyScroll);
pnl.add(userInfo);
pnl.add(msgInfo);
pnl.add(bodyLabel);
pnl.add(bodyScroll);
contentPane.add("North", pnl);
setVisible(true);
}
}
In my main class I am just creating a new gui and then calling the addElements() function.
FlowLayout doesn't "wrap" well. Consider a different layout, GridBagLayout for example...
Also, stop "trying" to force a size onto your UI, you don't have enough control over the factors which affect sizing to do this.
Instead, rely on the layout managers and API functionality. For example, instead of calling setSize on your frame, call pack...I would have posted soon, but it took me this long to find that call...I was scratching my head wondering why the UI wouldn't layout the way I expected...
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.LineBorder;
public class Test extends JFrame {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
Test frame = new Test("Testing", 400, 400);
}
});
}
Test(String title, int x, int y) {
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
addElements();
pack();
setVisible(true);
// setResizable(false);
}
public void addElements() {
Font size30 = new Font(null, Font.PLAIN, 30);
//--- User Info ---//
JPanel userInfo = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 4, 2);
gbc.gridx = 0;
gbc.gridy = 0;
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel, gbc);
gbc.gridx++;
userInfo.add(userField, gbc);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
gbc.gridx++;
userInfo.add(passLabel, gbc);
gbc.gridx++;
userInfo.add(passField, gbc);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
gbc.gridx++;
userInfo.add(serverLabel, gbc);
gbc.gridx++;
userInfo.add(serverField, gbc);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
gbc.gridx++;
userInfo.add(portLabel, gbc);
gbc.gridx++;
userInfo.add(portField, gbc);
gbc = new GridBagConstraints();
gbc.insets = new Insets(2, 2, 4, 2);
gbc.gridx = 0;
gbc.gridy = 0;
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel(new GridBagLayout());
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel, gbc);
gbc.gridx++;
msgInfo.add(toField, gbc);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
gbc.gridx++;
msgInfo.add(subLabel, gbc);
gbc.gridx++;
msgInfo.add(subField, gbc);
//--- Body ---//
// JPanel bodyPnl = new JPanel(new GridBagLayout());
// gbc = new GridBagConstraints();
// gbc.insets = new Insets(2, 2, 4, 2);
// gbc.gridx = 0;
// gbc.gridy = 0;
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setHorizontalAlignment(JLabel.CENTER);
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30, 70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
// bodyScroll.setBounds(getX(), getY(), bodyField.getWidth(), bodyField.getHeight());
setLayout(new GridBagLayout());
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(userInfo, gbc);
gbc.gridy++;
add(msgInfo, gbc);
gbc.gridy++;
gbc.insets = new Insets(10, 10, 4, 10);
add(bodyLabel, gbc);
gbc.gridy++;
gbc.insets = new Insets(4, 10, 10, 10);
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(bodyScroll, gbc);
}
}
The problem is because of FlowLayout Manager is being used. I have solved your problem with a different layout manager.
Before posting the solution here are some tips that you should follow
Change your class name. It should be in camel-case
Try to call pack() instead of setSize() as it will handle it automatically. When I replaced your setSize() with pack(), it was showing a awkward looking GUI which proves your layout and adding elements were not proper.
Font size30 = new Font(null, Font.PLAIN, 30);
JPanel pnl = new JPanel();
pnl.setLayout(new BoxLayout(pnl,BoxLayout.Y_AXIS));
Container contentPane = getContentPane();
//--- User Info ---//
JPanel userInfo = new JPanel();
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel);
userInfo.add(userField);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
userInfo.add(passLabel);
userInfo.add(passField);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
userInfo.add(serverLabel);
userInfo.add(serverField);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
userInfo.add(portLabel);
userInfo.add(portField);
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel();
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel);
msgInfo.add(toField);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
msgInfo.add(subLabel);
msgInfo.add(subField);
//--- Body ---//
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30,70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bodyScroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
pnl.add(userInfo);
pnl.add(msgInfo);
pnl.add(bodyLabel);
pnl.add(bodyScroll);
contentPane.add(pnl);
setVisible(true);
pack();

How can I align the JLabel to the left of the panel

I want to align all the JLabels to the left side of the panel. Following is my code, but it doesnt work properly, I dont know why.
JFrame frame1 = new JFrame("Register a passenger");
frame1.setVisible(true);
frame1.setSize(550, 200);
JPanel panel = new JPanel();
frame1.add(panel);
JLabel label1 = new JLabel("Name",SwingConstants.LEFT);
JLabel label2 = new JLabel("Activities",SwingConstants.LEFT);
JButton jbtReg = new JButton("Register");
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(jbtReg);
Based on your example, you could use
JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
But this will align all your components to the left.
You could also consider using a different layout manager or combination of layout managers?
Take a look at A Visual Guide to Layout Managers for more ideas
Updated
FlowLayout (which is the default layout manager for JPanel) doesn't give you a lot of options, instead consider trying to use a different layout manager or combination of layout managers, for example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class LayoutExample {
public static void main(String[] args) {
new LayoutExample();
}
public LayoutExample() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
add(new JLabel("Name:"), gbc);
gbc.gridy++;
add(new JLabel("Activity:"), gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
add(new JTextField(10), gbc);
gbc.gridy++;
add(new JTextField(20), gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
gbc.gridwidth = 2;
add(new JButton("Register"), gbc);
}
}
}

Why is my JmenuBar not showing

I'm working on a simple gui.
I can't seem to spot the reason as to why my JMenuBar Is not appearing. What am i missing?
Here is the code below.
myMenuBar = new JMenuBar();
myFileMenu = new JMenu("File");
myRegisterItem = new JMenuItem("Register");
myMenuBar.add(myFileMenu);
myFileMenu.add(myRegisterItem);
setJMenuBar(myMenuBar);
The full class:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.rmi.Naming;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
public class GUI extends JFrame{
private JTextArea recievedField;
private JButton sendButton;
private JTextField messageField;
private JComboBox itemComboBox;
private JButton connectButton;
private JTextField userNameField;
private JPasswordField passwordField;
private JButton loginButton;
private JMenuBar myMenuBar;
private JMenu myFileMenu;
private JMenuItem myRegisterItem;
public static void main(String[] args) {
new GUI();
}
public GUI() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new MainPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class MainPane extends JPanel {
public MainPane() {
myMenuBar = new JMenuBar();
setJMenuBar(myMenuBar);
myFileMenu = new JMenu("File");
myRegisterItem = new JMenuItem("Register");
myMenuBar.add(myFileMenu);
myFileMenu.add(myRegisterItem);
setBorder(new EmptyBorder(4, 4, 4, 4));
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(new LoginPane(), gbc);
gbc.gridy++;
add(new ConnectPane(), gbc);
gbc.gridy++;
gbc.weighty = 1;
gbc.fill = GridBagConstraints.BOTH;
add(new JScrollPane(recievedField = new JTextArea(5, 20)), gbc);
gbc.gridwidth = 1;
messageField = new JTextField(10);
sendButton = new JButton("Send");
gbc.gridy++;
gbc.weighty = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(messageField, gbc);
gbc.gridx++;
gbc.weightx = 0;
gbc.insets = new Insets(5,5,5,5);
add(sendButton, gbc);
}
}
public class ConnectPane extends JPanel {
public ConnectPane() {
itemComboBox = new JComboBox();
itemComboBox.addItem("Select an Item");
connectButton = new JButton("Connect");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5,5,5,5);
add(itemComboBox, gbc);
gbc.gridx++;
gbc.weightx = 1;
gbc.insets = new Insets(5,5,5,5);
add(connectButton, gbc);
}
}
public class LoginPane extends JPanel {
public LoginPane() {
userNameField = new JTextField(10);
passwordField = new JPasswordField(10);
loginButton = new JButton("Login");
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(5,5,5,5);
add(new JLabel("User name:"), gbc);
gbc.gridx++;
gbc.insets = new Insets(5,5,5,5);
add(userNameField, gbc);
gbc.gridx++;
gbc.insets = new Insets(5,5,5,5);
add(new JLabel("Password:"), gbc);
gbc.gridx++;
gbc.insets = new Insets(5,5,5,5);
add(passwordField, gbc);
gbc.gridx++;
gbc.weightx = 1;
add(loginButton, gbc);
}
}
Your problem is you call setJMenuBar on JPanel instance this is wrong you should call:
frame.setJMenuBar(myMenuBar);
Also no need for:
frame.setLayout(new BorderLayout());
as JFrame contentPane Layout by default is BorderLayout
i.e change your code to:
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPane());
frame.setJMenuBar(myMenuBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Also do not use EventQueue rather SwingUtilities:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MainPane());
frame.setJMenuBar(myMenuBar);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
Dont forget to comment out the setJmenuBar(..) in your MainPane class:
public MainPane() {
myMenuBar = new JMenuBar();
//notice no call to setJMenuBar
myFileMenu = new JMenu("File");
myRegisterItem = new JMenuItem("Register");
myMenuBar.add(myFileMenu);
...
}
Its because you have not set Your JMenuBar Visible.
Add this to your code
frame.setJMenuBar(myMenuBar); // This line to be added
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Categories