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);
Related
I am trying to move a table to the left side of a JPanel which is also inside a Window
What I get is this:
What I want is this:
I tried using .setBounds method but it does not work. Does anyone know what to do?
This is my code:
package Modulos;
import paneles.*;
import javax.swing.*;
public class ModuloAdmin extends JFrame {
public ModuloAdmin(){
//Crear tabla
String[][] datosprueba = {
{"001","Carlitos", "Casa","51202011"},
{"001","Carlitos", "Casa","51202011"}
};
String[] TituloColumna = {"Código", "Nombre", "Dirección", "Teléfono"};
JTable TablaSucursales = new JTable(datosprueba,TituloColumna);
//Contenido de las pestañas
JPanel PanelSucursales = new JPanel();
PanelSucursales.add(TablaSucursales);
PanelSucursales.add(new JScrollPane(TablaSucursales));
JPanel PanelProductos = new JPanel();
PanelProductos.add(new JLabel("Panel productos"));
JPanel PanelClientes = new JPanel();
PanelClientes.add(new JLabel("Panel Clientes"));
JPanel PanelVendedores = new JPanel();
PanelVendedores.add(new JLabel("Panel Vendedores"));
//CREACION DE PESTAÑAS
JTabbedPane Pestanias = new JTabbedPane();
Pestanias.setBounds(20,80,700,700);
Pestanias.add("Sucursales",PanelSucursales);
Pestanias.add("Productos",PanelProductos);
Pestanias.add("Clientes", PanelClientes);
Pestanias.add("Vendedores",PanelVendedores);
//vENTANA MODULO DE ADMIN
JFrame VentanaModuloAdmin = new JFrame();
VentanaModuloAdmin.add(Pestanias);
VentanaModuloAdmin.setLayout(null);
VentanaModuloAdmin.setSize(800,850);
VentanaModuloAdmin.setLocationRelativeTo(null);
VentanaModuloAdmin.setTitle("Módulo de administrador");
VentanaModuloAdmin.setVisible(true);
VentanaModuloAdmin.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
Use appropriate layout mangers and container management
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.EmptyBorder;
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 {
private JTable table;
public TestPane() {
setBorder(new EmptyBorder(16, 16, 16, 16));
setLayout(new GridLayout(0, 2));
add(new JScrollPane(table));
add(createButtonPane());
}
protected JPanel createButtonPane() {
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 16;
gbc.ipady = 16;
gbc.fill = gbc.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(new JButton("Clear"), gbc);
gbc.gridx = 1;
panel.add(new JButton("Carga Masiva"), gbc);
gbc.gridy++;
gbc.gridx = 0;
panel.add(new JButton("Actualizar"), gbc);
gbc.gridx = 1;
panel.add(new JButton("Eliminar"), gbc);
gbc.gridy++;
gbc.gridx = 0;
gbc.gridwidth = 2;
gbc.anchor = GridBagConstraints.NORTH;
gbc.weighty = 1;
panel.add(new JButton("Exportar Listado a PDF"), gbc);
return panel;
}
}
}
Seriously, layout managers solve one of the most difficult issues facing UI developers - the variable nature of the output (screen resolutions, font metrics, accessibility modifiers, a whole bunch of different stuff which changes how layouts need to be calculated).
They might seem difficult to start with, but once you get use to using them and learn how to make use of "compound layouts", which is demonstrated above, it will help you make better UIs more quickly
How can I replace a JPanel or JFrame & its contents with another one by a simple button click in the same container ?
here a simple example that you can follow please show code at lest so we can follow your problem this a snap of code from unknowing source (old one)
package layout;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class CardLayoutExample extends JFrame{
JPanel totelPanel,btnPan,showPan;
JButton btn1,btn2;
public static void main(String[] args) {
CardLayoutExample ex = new CardLayoutExample();
ex.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ex.pack();
ex.setLocationRelativeTo(null);
ex.setTitle("BookClube library system");
ex.setVisible(true);
}
public CardLayoutExample(){
btn1 = new JButton("menu button");
btn2 = new JButton("back button");
CardLayout c1 = new CardLayout();
btnPan = new JPanel();
btnPan.add(btn1);
showPan = new JPanel();
showPan.add(btn2);
totelPanel = new JPanel(c1);
totelPanel.add(btn1,"1");
totelPanel.add(btn2,"2");
c1.show(totelPanel,"1");
JPanel fullLayout = new JPanel(new BorderLayout());
fullLayout.add(totelPanel,BorderLayout.NORTH);
add(fullLayout);
btn1.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"2");
}
});
btn2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
c1.show(totelPanel,"1");
}
});
}
}
The trick would be to use CardLayout or modify panel visibility.
Please look at the following example that modifies panel visibility.
public class PanelExample {
private JPanel _myPanel1,_myPanel2;
public void init() {
JFrame frame = new JFrame("Testing");
JPanel mainPanel = new JPanel(new GridBagLayout());
_myPanel1 = new JPanel();
_myPanel1.add(new JLabel("Panel 1"));
_myPanel1.setVisible(true);
_myPanel2 = new JPanel();
_myPanel2.add(new JLabel("Panel 2"));
_myPanel2.setVisible(false);
JButton button = new JButton("Switch to Panel2");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(_myPanel1.isVisible()) {
_myPanel1.setVisible(false);
_myPanel2.setVisible(true);
button.setText("Switch to Panel1");
} else {
_myPanel1.setVisible(true);
_myPanel2.setVisible(false);
button.setText("Switch to Panel2");
}
}
});
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.PAGE_START;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.weighty = 0;
mainPanel.add(button,gbc);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.BOTH;
gbc.gridwidth = 2;
gbc.gridheight = 2;
gbc.weightx = 1;
gbc.weighty = 1;
mainPanel.add(_myPanel1,gbc);
mainPanel.add(_myPanel2,gbc);
frame.add(mainPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
PanelExample exmp = new PanelExample();
exmp.init();
}
}
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
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);
}
}
}
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();