I am making a form using the GridBag
layout which has a titled border. The first TitledBorder
panel
which is Customer Details works fine except that I would like to know how add some spacing between the first title and textfield
(eg first name) and the following title and textfield
(eg last name) below it.
The problem with the second panel
which is Room Details is that it expands as I enlarge/expand the window and as this happens, the components inside it also shift. I would like it to remain fixed like the components in the first panel
.
This is the form.java class:
public class form extends JFrame{
JPanel pnl= new JPanel();
JPanel pnl1= new JPanel();
JLabel fname= new JLabel("First name: ");
JLabel lname= new JLabel("Last name: ");
JLabel contact= new JLabel("Contact number: ");
JLabel email= new JLabel("Email address: ");
JLabel address= new JLabel("Address: ");
JLabel numpsns= new JLabel("Number of persons: ");
JTextField fnameField= new JTextField(25);
JTextField lnameField= new JTextField(25);
JTextField contactField= new JTextField(25);
JTextField emailField= new JTextField(25);
JTextArea txtadd= new JTextArea(5, 25);
SpinnerModel sm= new SpinnerNumberModel(1,0,30,1);
JSpinner spinner= new JSpinner(sm);
public form(){
this.setTitle("Reservation Form");
pnl.setBorder(new TitledBorder(null,"Customer Details", TitledBorder.CENTER, TitledBorder.TOP, null, null));
getContentPane().add(pnl, BorderLayout.NORTH);
pnl.setLayout(new GridBagLayout());
GridBagConstraints gc= new GridBagConstraints();
//first column of the grid//
gc.anchor= GridBagConstraints.EAST;
gc.weightx=0.5;
gc.weighty=0.5;
gc.gridx=0;
gc.gridy=0;
pnl.add(fname, gc);
gc.gridx=0;
gc.gridy=1;
pnl.add(lname,gc);
gc.gridx=0;
gc.gridy=2;
pnl.add(contact, gc);
gc.gridx=0;
gc.gridy=3;
pnl.add(email, gc);
gc.gridx=0;
gc.gridy=4;
pnl.add(address, gc);
//second column//
gc.anchor= GridBagConstraints.WEST;
gc.gridx=1;
gc.gridy= 0;
pnl.add(fnameField,gc);
gc.gridx=1;
gc.gridy=1;
pnl.add(lnameField, gc);
gc.gridx=1;
gc.gridy=2;
pnl.add(contactField, gc);
gc.gridx=1;
gc.gridy=3;
pnl.add(emailField, gc);
gc.gridx=1;
gc.gridy=4;
pnl.add(txtadd, gc);
//second Titled Border//
pnl1.setBorder(BorderFactory.createTitledBorder(null, "Booking Details", TitledBorder.CENTER, TitledBorder.CENTER));
add(pnl1, BorderLayout.CENTER);
pnl1.setLayout(new GridBagLayout());
GridBagConstraints gc1= new GridBagConstraints();
//first column//
gc1.weightx= 0.5;
gc1.weighty=0.5;
gc1.gridx=0;
gc1.gridy=0;
pnl1.add(numpsns, gc1);
gc1.anchor= GridBagConstraints.WEST;
gc1.gridx=1;
gc1.gridy= 0;
pnl1.add(spinner,gc1);
}
}
form_main.java class
public class form_main {
public static void main(String[] args) {
form form_display= new form();
form_display.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
form_display.pack();
form_display.setSize(500,280);
form_display.setVisible(true);
}
}