Search code examples
javaswinggridbaglayouttitled-border

Java- TitledBorder in gridbag layout expanding as the window expands


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

    }

 }

Here is a screenshot of how it is: enter image description here


Solution

  • You've added the second panel to the CENTRE position of a BorderLayout, this is the expected behaviour for this type of layout. Perhaps you should use another GridBagLayout to layout the two panels

    To add internal spacing to the panel you could use a CompoundLayout, wrapping the TitledBorder and an EmptyBorder together or set the GridBagConstraints#insets property

    Simple example...

    Simple

    import java.awt.EventQueue;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.BorderFactory;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSpinner;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    import javax.swing.SpinnerModel;
    import javax.swing.SpinnerNumberModel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.border.Border;
    import javax.swing.border.CompoundBorder;
    import javax.swing.border.EmptyBorder;
    import javax.swing.border.TitledBorder;
    
    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");
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.fill = gbc.HORIZONTAL;
    
            Border border = new CompoundBorder(
                    new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, null, null),
                    new EmptyBorder(10, 10, 10, 10));
    
            pnl.setBorder(border);
            getContentPane().add(pnl, gbc);
    
            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, gbc);
    
            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);
    
        }
    
        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) {
                        ex.printStackTrace();
                    }
    
                    Form frame = new Form();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
    }
    

    Thanks a lot. Can you show me how I can change the font and size of the titles(like Customer Details, Booking Details) of the borders? Font.BOLD doesn't seem to work in createTitledBorder

    ...

    new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, UIManager.getFont("Label.font").deriveFont(Font.BOLD), null);

    ...

    That didn't work

    Works fine for me...

    TitledBorder

    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.border.TitledBorder;
    
    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());
                JPanel p1 = new JPanel();
                p1.setBorder(new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, null, null));
                JPanel p2 = new JPanel();
                p2.setBorder(new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, UIManager.getFont("Label.font").deriveFont(Font.BOLD), null));
                JPanel p3 = new JPanel();
                p3.setBorder(new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, UIManager.getFont("Label.font").deriveFont(Font.ITALIC), null));
                JPanel p4 = new JPanel();
                p4.setBorder(new TitledBorder(null, "Customer Details", TitledBorder.CENTER, TitledBorder.TOP, UIManager.getFont("Label.font").deriveFont(Font.BOLD | Font.ITALIC), null));
    
                GridBagConstraints gbc = new GridBagConstraints();
                gbc.gridwidth = GridBagConstraints.REMAINDER;
                gbc.weightx = 1;
                gbc.weighty = 1;
                gbc.fill = GridBagConstraints.BOTH;
    
                add(p1, gbc);
                add(p2, gbc);
                add(p3, gbc);
                add(p4, gbc);
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
        }
    
    }