GridBagLayout

Hi,
I am trying to create a JDialog which has three panels on it. The left panel has the same height as the dialog, and a fixed width that I specify (say 300 pixels). If the dialog is enlarged, it expands vertically. The right panel is to the right of this, and the bottom panel is below the right panel. The bottom panel has a fixed height, but its width can change if the dialog is enlarged. It only needs to be about 100 pixels high. There are no gaps, i.e. the width of the right and bottom panels is the width of the dialog, minus the width of the left panel. The right panel can expand in both width and height if the dialog is enlarged.
I have had a lot of trouble with this, and the closest that I have come is by modifying a demo of the dreaded GridBagLayout, thus:
import java.awt.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GridBagLayoutDemo {
    public static void addComponentsToPane(Container pane) {
     pane.setLayout(new GridBagLayout());
     GridBagConstraints c = new GridBagConstraints();
     //c.fill = GridBagConstraints.HORIZONTAL;
     JPanel left = new JPanel();
        left.setBackground(Color.RED);
        left.setPreferredSize(new Dimension(100,500));
     c.weightx = 0.5;
     c.fill = GridBagConstraints.VERTICAL;
     c.gridx = 0;
     c.gridy = 0;
        c.weighty=1.0; 
        c.gridheight = 2;
     pane.add(left, c);
     JPanel right = new JPanel();
        right.setPreferredSize(new Dimension(500,400));
        right.setBackground(Color.BLUE);
     c.fill = GridBagConstraints.BOTH;
     c.weightx = 0.5;
     c.gridx = 1;
     c.gridy = 0;
        c.gridheight =1;
        c.weighty=0; 
     pane.add(right, c);
     JPanel bottom = new JPanel();
        bottom.setPreferredSize(new Dimension(500,100));
        bottom.setBackground(Color.GREEN);
     c.fill = GridBagConstraints.HORIZONTAL;
     c.weighty = 1.0; 
     c.gridx = 1;    
     c.gridy = 1;    
     pane.add(bottom, c);
    private static void createAndShowGUI() {
        JFrame frame = new JFrame("GridBagLayoutDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addComponentsToPane(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
}It looks ok initially but when you resize, there are lots of horrible white spaces. I want the right panel (coloured blue) to stay adjacent to the left panel (coloured red), and likewise with the bottom panel (coloured green). Also, when the window is shrunk smaller than its original size, the right panel suddenly reduces to being tiny. Can anyone help, please?

     * modified version - look closely ;-)
    public static void addComponentsToPane(Container pane) {
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        JPanel left = new JPanel();
        left.setBackground(Color.RED);
        left.setPreferredSize(new Dimension(100,500));
        c.fill = GridBagConstraints.BOTH;
        c.weightx = 0.5;
        c.weighty = 1;
        c.gridx = 0;
        c.gridy = 0;
        c.gridheight = 2;
        pane.add(left, c);
        JPanel right = new JPanel();
        right.setPreferredSize(new Dimension(500,400));
        right.setBackground(Color.BLUE);
        c.gridx = 1;
        c.gridy = 0;
        c.gridheight = 1;
        pane.add(right, c);
        JPanel bottom = new JPanel();
        bottom.setPreferredSize(new Dimension(500,100));
        bottom.setBackground(Color.GREEN);
        c.fill = GridBagConstraints.HORIZONTAL;
        c.weightx = 1;
        c.weighty = 0;
        c.gridx = 1;
        c.gridy = 1;
        pane.add(bottom, c);
    }For components with fill BOTH, you need to specify weightx and weighty, for HORIZONTAL weightx, and for VERTICAL weighty. I usually set weighty to 0 for HORIZONTAL and weightx to 0 for VERTICAL just to be safe.

Similar Messages

  • GridBagLayout and Panel Border problem

    I have 3 panels like
    A
    B
    C
    and the C panel has a Mouse Listener that on a mouseEntered creates a border around the same panel and on a mouseExited clears that border.
    When this border is created the A and B panels go up a little bit .. they move alone when the border is created.
    Is there any way to fix this problem? Is there any way to get the panels static?
    the code is close to the following:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.MouseListener;
    import java.awt.event.MouseEvent;
    import javax.swing.BorderFactory;
    import javax.swing.border.Border;
    import javax.swing.border.TitledBorder;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener
    JPanel game, options, top, down, middle;
    NumberFormat nf;
    public Game() {
    super("Game");
    nf = NumberFormat.getPercentInstance();
    nf.setMaximumFractionDigits(1);
    JPanel center = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = gbc.BOTH;
    gbc.weighty = 1.0;
    gbc.weightx = 0.8;
    center.add(getGamePanel(), gbc);
    gbc.weightx = 0.104;
    center.add(getOptionsPanel(), gbc);
    Container cp = getContentPane();
    // use the JFrame default BorderLayout
    cp.add(center); // default center section
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setSize(700,600);
    // this.setResizable(false);
    setLocationRelativeTo(null);
    setVisible(true);
    addComponentListener(new ComponentAdapter()
    public void componentResized(ComponentEvent e)
    showSizeInfo();
    showSizeInfo();
    private void showSizeInfo()
    Dimension d = getContentPane().getSize();
    double totalWidth = game.getWidth() + options.getWidth();
    double gamePercent = game.getWidth() / totalWidth;
    double optionsPercent = options.getWidth() / totalWidth;
    double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
    double topPercent = top.getHeight() / totalHeight;
    double middlePercent = middle.getHeight() / totalHeight;
    double downPercent = down.getHeight() / totalHeight;
    System.out.println("content size = " + d.width + ", " + d.height + "\n" +
    "game width = " + nf.format(gamePercent) + "\n" +
    "options width = " + nf.format(optionsPercent) + "\n" +
    "top height = " + nf.format(topPercent) + "\n" +
    "middle height = " + nf.format(middlePercent) + "\n" +
    "down height = " + nf.format(downPercent) + "\n");
    private JPanel getGamePanel()
    // init components
    top = new JPanel(new BorderLayout());
    top.setBackground(Color.red);
    top.add(new JLabel("top panel", JLabel.CENTER));
    middle = new JPanel(new BorderLayout());
    middle.setBackground(Color.green.darker());
    middle.add(new JLabel("middle panel", JLabel.CENTER));
    down = new JPanel(new BorderLayout());
    down.setBackground(Color.blue);
    down.add(new JLabel("down panel", JLabel.CENTER));
    // layout game panel
    game = new JPanel(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.fill = gbc.BOTH;
    gbc.gridwidth = gbc.REMAINDER;
    gbc.weighty = 0.2;
    game.add(top, gbc);
    gbc.weighty = 0.425;
    game.add(middle, gbc);
    gbc.weighty = 0.2;
    game.add(down, gbc);
    down.addMouseListener(this);
    return game;
    private JPanel getOptionsPanel()
    options = new JPanel(new BorderLayout());
    options.setBackground(Color.pink);
    options.add(new JLabel("options panel", JLabel.CENTER));
    return options;
    // mouse listener events
         public void mouseClicked( MouseEvent e ) {
    System.out.println("pressed");
         public void mousePressed( MouseEvent e ) {
         public void mouseReleased( MouseEvent e ) {
         public void mouseEntered( MouseEvent e ) {
    Border redline = BorderFactory.createLineBorder(Color.red);
    JPanel x = (JPanel) e.getSource();
    x.setBorder(redline);
         public void mouseExited( MouseEvent e ){
    JPanel x = (JPanel) e.getSource();
    x.setBorder(null);
    public static void main(String[] args ) {
    Game exe = new Game();
    exe.show();
    }

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.event.*;
    import java.text.NumberFormat;
    public class Game extends JFrame implements MouseListener{
      JPanel game, options, top, down, middle;
      NumberFormat nf;
      public Game() {
        super("Game");
        nf = NumberFormat.getPercentInstance();
        nf.setMaximumFractionDigits(1);
        JPanel center = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = gbc.BOTH;
        gbc.weighty = 1.0;
        gbc.weightx = 0.8;
        center.add(getGamePanel(), gbc);
        gbc.weightx = 0.104;
        center.add(getOptionsPanel(), gbc);
        Container cp = getContentPane();
        // use the JFrame default BorderLayout
        cp.add(center); // default center section
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(700,600);
        // this.setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
        addComponentListener(new ComponentAdapter(){
            public void componentResized(ComponentEvent e){
            showSizeInfo();
        showSizeInfo();
      private void showSizeInfo(){
        Dimension d = getContentPane().getSize();
        double totalWidth = game.getWidth() + options.getWidth();
        double gamePercent = game.getWidth() / totalWidth;
        double optionsPercent = options.getWidth() / totalWidth;
        double totalHeight = top.getHeight() + middle.getHeight() + down.getHeight();
        double topPercent = top.getHeight() / totalHeight;
        double middlePercent = middle.getHeight() / totalHeight;
        double downPercent = down.getHeight() / totalHeight;
        System.out.println("content size = " + d.width + ", " + d.height + "\n" +
            "game width = " + nf.format(gamePercent) + "\n" +
            "options width = " + nf.format(optionsPercent) + "\n" +
            "top height = " + nf.format(topPercent) + "\n" +
            "middle height = " + nf.format(middlePercent) + "\n" +
            "down height = " + nf.format(downPercent) + "\n");
      private JPanel getGamePanel(){
        // init components
        top = new JPanel(new BorderLayout());
        top.setBackground(Color.red);
        top.add(new JLabel("top panel", JLabel.CENTER));
        middle = new JPanel(new BorderLayout());
        middle.setBackground(Color.green.darker());
        middle.add(new JLabel("middle panel", JLabel.CENTER));
        down = new JPanel(new BorderLayout());
        down.setBackground(Color.blue);
        down.add(new JLabel("down panel", JLabel.CENTER));
        // layout game panel
        game = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.fill = gbc.BOTH;
        gbc.gridwidth = gbc.REMAINDER;
        gbc.weighty = 0.2;
        game.add(top, gbc);
        gbc.weighty = 0.425;
        game.add(middle, gbc);
        gbc.weighty = 0.2;
        game.add(down, gbc);
        down.addMouseListener(this);
        return game;
      private JPanel getOptionsPanel(){
        options = new JPanel(new BorderLayout());
        options.setBackground(Color.pink);
        options.add(new JLabel("options panel", JLabel.CENTER));
        return options;
      public void mouseClicked( MouseEvent e ) {
        System.out.println("pressed");
      public void mousePressed( MouseEvent e ) {
      public void mouseReleased( MouseEvent e ) {
      public void mouseEntered( MouseEvent e ) {
        Border redline = new CalmLineBorder(Color.red);
        JPanel x = (JPanel) e.getSource();
        x.setBorder(redline);
      public void mouseExited( MouseEvent e ){
        JPanel x = (JPanel) e.getSource();
        x.setBorder(null);
      public static void main(String[] args ) {
        Game exe = new Game();
        exe.setVisible(true);
    class CalmLineBorder extends LineBorder{
      public CalmLineBorder(Color c){
        super(c);
      public CalmLineBorder(Color c, int thick){
        super(c, thick);
      public CalmLineBorder(Color c, int thick, boolean round){
        super(c, thick, round);
      public Insets getBorderInsets(Component comp){
        return new Insets(0, 0, 0, 0);
    }

  • GridBagLayout Problem

    I have a jframe in which i want to display 2 jpanels (panelA, panelB).
    The arrangement for panelA is at cell (1,1) and for panelB at cell(1,3)
    cell(0,0) upper-left
    Here is my code:
    GridBagLayout gridBag = new GridBagLayout();
    GridBagConstraints constr = new GridBagConstraints();
    mainFrame = new JFrame("MAIN-FRAME");
    mainFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
    aDesktopPane = new JDesktopPane();
    aDesktopPane.setBackground(Color.LIGHT_GRAY);
    aDesktopPane.setDragMode(JDesktopPane.OUTLINE_DRAG_MODE);
    mainFrame.setContentPane(aDesktopPane);
    mainFrame.getContentPane().setLayout(gridBag);
    BuildConstraints(constr,0,1,1,1,30,0);
    constr.fill=GridBagConstraints.BOTH;
    constr.insets = createFeatures.Inset(3,3,3,3);
    JPanel justForLayout = new JPanel(gridBag); //i use this panel for helping me at the arrangment
    justForLayout.setBackground(Color.LIGHT_GRAY);
    mainFrame.getContentPane().add(justForLayout,constr);
    BuildConstraints(constr,1,1,1,1,40,70);
    constr.fill = GridBagConstraints.HORIZONTAL;
    constr.insets = createFeatures.Inset(3,3,3,3);
    mainFrame.getContentPane().add(panelA, constr);
    BuildConstraints(constr,2,1,1,1,30,0);
    constr.fill=GridBagConstraints.BOTH;
    constr.insets = createFeatures.Inset(3,3,3,3);
    JPanel justForLayout2 = new JPanel(gridBag);//i use this panel for helping me at the arrangment
    justForLayout2.setBackground(Color.LIGHT_GRAY);
    mainFrame.getContentPane().add(justForLayout2,constr);
    BuildConstraints(constr,1,3,1,1,0,30);
    constr.fill = GridBagConstraints.HORIZONTAL;
    constr.insets = createFeatures.Inset(3,3,3,3);
    mainFrame.getContentPane().add(panelB, constr);
    public void BuildConstraints (GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) {
         gbc.gridx = gx;
         gbc.gridy = gy;
         gbc.gridwidth = gw;
         gbc.gridheight = gh;
         gbc.weightx = wx;
         gbc.weighty = wy;
    }//end method Buildconstrraints()

    Try this as a demo, you may have to work with it a bit.
           JPanel mainPanel = (JPanel) getContentPane();
            mainPanel.setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            JPanel PanelA = new JPanel();
            PanelA.setBorder(BorderFactory.createEtchedBorder());
            PanelA.add(new JLabel("I'm panel A"));
            JPanel PanelB = new JPanel();
            PanelB.setBorder(BorderFactory.createEtchedBorder());
            PanelB.add(new JLabel("I'm Panel B"));
            gbc.anchor = GridBagConstraints.WEST;
            gbc.fill = GridBagConstraints.BOTH;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbc.insets = new Insets(40, 10, 40, 10);    //top,left,bottom,right
            mainPanel.add(PanelA, gbc);
            mainPanel.add(PanelB, gbc);

  • Problem with gridbaglayout in JPanel

    Hello I am trying to display contact information in three serperate Jpanels on tabbbed panes.I would like to get help in configuring maybe just the pane of void showPane1().I need something like
    Searchlb | Combodropname1
    firstnamelb | firstnametxt | lastnamelb | lastnametxt
    Addresslb addresslb.Horizontal-----------------------*-
    citylb | citytxt | statelb | statetxt
    postcodelb | postcodetxt | countrylb | countrytxt
    emaillb | emailtxt | homephonelb | homephonetxt
    faxnumberlb | faxnumbertxt
    Other panes have buttons
    Here`s the code it operates on login of MSAccess table called persons:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    import java.io.*;
    import java.util.Date;
    import java.text.NumberFormat;
    public class Addressbook extends JFrame{
         // Define constant variables
         final static String driver      = "sun.jdbc.odbc.JdbcOdbcDriver";
         final static String url      = "jdbc:odbc:addBKTAFE";
         final static String login      = "LOG-IN";
         final static String tab_login      = "Log-in";
         final static String tab1      = "INQUIRE Personnel Details";
         final static String tab2      = "UPDATE/DELETE Personnel Details";
         final static String tab3      = "INSERT Personnel Details";
         final static String insert      = "SAVE RECORD";
         final static String update           = "UPDATE RECORD";
         final static String delete      = "DELETE RECORD";
         final static String inquire      = "INQUIRE RECORD";
         final static String clear      = " CLEAR ";
         final static String relogin      = "Log-in failed! Please relog-in!";
         final static String norecfound      = "No Record Found!";
         final static String recinserted     = "Record Inserted!";
         final static String recupdated      = "Record Updated!";
         final static String recdeleted      = "Record Deleted!";
         final static String numericerror = "Age should be numeric!";
         final static String information = "INFORMATION";
         final static String error      = "ERROR";
         final static String genexception = "GENERAL EXCEPTION";
         final static String sqlexception = "SQL EXCEPTION";
         final static String confdelete = "CONFIRM DELETE";
         final static String slash      = "/";
         final static String table1      = "persons";
         final static String table2      = "Addresses";
    // Events events = new Events(this);
         // Define variables     for general use
         String sql = ""; // Used to store sql statements
         int pane_number = 0; // Used to indicate what screen needs to be processed
                                       // like resetting input fields and comboboxes
         boolean abort = false;// Used to indicate if error found to avoid further
                                       // processing/validations
         // Define container, panels and tabbedpane
    Container cntr = getContentPane();
    JTabbedPane tpane = new JTabbedPane();
         JPanel      cbpanel1 , cbpanel2 , cbpanel3,
                   panel1 , panel2 , panel3;
         // Setup constraints and type of layout
         GridBagConstraints constraints = new GridBagConstraints();
         GridBagConstraints constraints1 = new GridBagConstraints();
         GridBagConstraints constraints2 = new GridBagConstraints();
         GridBagConstraints constraints3 = new GridBagConstraints();
         GridBagLayout layout = new GridBagLayout ();
         // Define fonts to be used
         Font labelFont = new Font("Arial",Font.PLAIN,12);
         Font buttonFont = new Font("Arial",Font.BOLD,13);
         // Define labels
         JLabel lbUser      = new JLabel("Enter User ID: " );
         JLabel lbPassword      = new JLabel("Enter Password: ");
         JLabel lbSelectName      = new JLabel("Search Name: " );
         JLabel lbFirstName      = new JLabel("First Name: " );
         JLabel lbLastName      = new JLabel("Last Name: " );
         JLabel lbAddress           = new JLabel("Address: " );
         JLabel lbCity           = new JLabel("City" );
         JLabel lbState           = new JLabel("State: " );
         JLabel lbPostcode      = new JLabel("Postcode" );
    JLabel lbCountry           = new JLabel("Country" );
         JLabel lbEmailAddress      = new JLabel("Email Address: " );
    JLabel lbHomeNumber      = new JLabel("Home Phone No.: " );
    JLabel lbFaxNumber      = new JLabel("Fax No.: " );
         // Define combo boxes in third screen (insert pane)
         JComboBox cbName1          = new JComboBox();
         JComboBox cbPersonId1          = new JComboBox();
         // Define combo boxes in second (update/delete pane)
         JComboBox cbName2          = new JComboBox();
         JComboBox cbPersonId2          = new JComboBox();
         // Define buttons, text fields and password field
         JButton btLogin      = new JButton (login );
         JButton btInsert = new JButton (insert );
         JButton btUpdate      = new JButton (update );
         JButton btDelete      = new JButton (delete );
         JButton btInquire      = new JButton (inquire);
         JButton btClear      = new JButton (clear );
         JPasswordField jpPassword           = new JPasswordField(10 );
         JTextField tfUser           = new JTextField("",10 );
         // Inquiry fields on first screen (inquiry pane)
         JTextField tfFirstName1      = new JTextField("",30);
         JTextField tfLastName1           = new JTextField("",30);
         JTextField      tfAddress1          = new JTextField("",30);
         JTextField      tfCity1 = new JTextField("",15);
         JTextField      tfState1 = new JTextField("",15);
         JTextField      tfPostcode1      = new JTextField("",30);
         JTextField      tfCountry1          = new JTextField("",15 );
    JTextField      tfEmailAddress1      = new JTextField("",30);
    JTextField      tfHomeNumber1      = new JTextField("",15);
         JTextField      tfFaxNumber1           = new JTextField("",15 );
         // Input fields on second screen (update/delete pane)
         JTextField tfFirstName2      = new JTextField("",30);
         JTextField tfLastName2          = new JTextField("",30);
         JTextField      tfAddress2          = new JTextField("",30);
         JTextField      tfCity2 = new JTextField("",15);
         JTextField      tfState2 = new JTextField("",15);
         JTextField      tfPostcode2      = new JTextField("",30);
         JTextField      tfCountry2          = new JTextField("",15 );
    JTextField      tfEmailAddress2      = new JTextField("",30);
    JTextField      tfHomeNumber2      = new JTextField("",15);
         JTextField      tfFaxNumber2      = new JTextField("",15 );
         // Input fields on third screen (insert pane)
         JTextField tfFirstName3      = new JTextField("",30);
         JTextField tfLastName3          = new JTextField("",30);
         JTextField      tfAddress3          = new JTextField("",30);
         JTextField      tfCity3 = new JTextField("",15);
         JTextField      tfState3 = new JTextField("",15);
         JTextField      tfPostcode3      = new JTextField("",30);
         JTextField      tfCountry3          = new JTextField("",15 );
    JTextField      tfEmailAddress3      = new JTextField("",30);
    JTextField      tfHomeNumber3      = new JTextField("",15);
         JTextField      tfFaxNumber3           = new JTextField("",15 );
    //------------------------------------------------------------------------------>>>
    //-----------------------Start Addressbook()------------------------------------>>>
    Addressbook(){
    // define listener after adding items to CB to avoid triggering it
         //     cbName1.addItemListener(new ItemListener());
    // public void itemStateChanged(ItemEvent e){
    //--------------------------END Addressbook constructor------------------------------------->>>
    //------------------------------------------------------------------------------>>>
    //------------------------------------------------------------------------------>>>
    //--------------------Start setupLoginPanel()----------------------------------->>>
         // Setup the login screen
         public void setupLoginPanel(){
              // set application title
         setTitle("Address Book Application");
              // center screen
              setLocation((Toolkit.getDefaultToolkit().getScreenSize().width
                                  - getWidth())/2,
                        (Toolkit.getDefaultToolkit().getScreenSize().height
                             - getHeight())/2);
         panel1 = new JPanel();
              // set screen border
              panel1.setBorder(BorderFactory.createTitledBorder(
                                  BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab_login, panel1);
              // add panel to container
              cntr.add(tpane);
              // setup layout as GridBagLayout
              constraints.insets = new Insets(2,2,2,2);
              panel1.setLayout(layout);
              // setup User ID label in display area
              lbUser.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 0;
              constraints.gridy = 0;
              constraints.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbUser, constraints);
              panel1.add(lbUser);
              // setup User ID input field in display area
              tfUser.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 1;
              constraints.gridy = 0;
              constraints.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfUser, constraints);
              panel1.add(tfUser);
              // setup Password label in display area
              lbPassword.setFont(labelFont);
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 0;
              constraints.gridy = 1;
              constraints.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPassword, constraints);
              panel1.add(lbPassword);
              // setup Password input field in display area
              jpPassword.setEchoChar('*');
              constraints.ipadx = 2;
              constraints.ipady = 2;
              constraints.gridx = 1;
              constraints.gridy = 1;
              layout.setConstraints(jpPassword, constraints);
              panel1.add(jpPassword);
              // setup Login button in display area
              btLogin.setFont(buttonFont);
              constraints.anchor = GridBagConstraints.WEST;
              constraints.gridy = 3;
              constraints.gridx = 1;
              layout.setConstraints(btLogin, constraints);
              panel1.add(btLogin);
              // setup login button listener
              btLogin.addActionListener(new ButtonHandler());
              // allow ALT L to press login button
              btLogin.setMnemonic('l');
    //--------------------End setupLoginPanel()------------------------------------->>>
    //--------------------Start login()--------------------------------------------->>>
         // Validate user input from the login screen based on information from login
         // table (note: manually create/update your login from table LOGIN).
         public void login(){
              String user = tfUser.getText();
              user = user.trim();
              char[] pw = jpPassword.getPassword();
    String password = new String(pw).trim();
              sql = "SELECT * FROM persons WHERE username='"+
                   user+"' AND password='"+password+"'";
              try{
                   // load MS Access driver
                   Class.forName(driver);
              }catch(java.lang.ClassNotFoundException ex){
                   JOptionPane.showMessageDialog(null,ex.getMessage(), error ,
                        JOptionPane.PLAIN_MESSAGE);
              try{
                   // setup connection to DBMS
                   Connection conn = DriverManager.getConnection(url);
                   // create statement
                   Statement stmt = conn.createStatement();
                   // execute sql statement
                   stmt.execute(sql);
                   ResultSet rs = stmt.getResultSet();
                   boolean recordfound = rs.next();
                   if (recordfound){
                        tpane.removeTabAt(0);
                        showPane1();
                        showPane2();
                        showPane3();
                   else{
                        // username/password invalid
                        JOptionPane.showMessageDialog(null,relogin, error,
                             JOptionPane.INFORMATION_MESSAGE);
                        //clear login and password fields
                        tfUser.setText ("");
                        jpPassword.setText("");
                   conn.close();
              }catch(Exception ex){
                   JOptionPane.showMessageDialog(null,ex.getMessage(), genexception,
                        JOptionPane.INFORMATION_MESSAGE);
    //--------------------End login()----------------------------------------------->>>
    //--------------------Start showPane1()----------------------------------------->>>
         // Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
         // Table PERSONS is read to list inquiry parameters.
         void showPane1(){
              panel1 = new JPanel();
              cbpanel1 = new JPanel();
              // set screen border
              panel1.setBorder(BorderFactory.createTitledBorder(
                                  BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab1, panel1);
              // setup layout as GridBagLayout
              constraints1.insets = new Insets(2,2,2,2);
              panel1.setLayout (layout);
              cbpanel1.setLayout (layout);
              // setup Name combobox label
              lbSelectName.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 0;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbSelectName, constraints1);
              panel1.add(lbSelectName);
              // setup Name combobox as search key
              cbName1.setFont(labelFont);
              constraints1.ipady = 10;
              constraints1.gridx = 1;
              constraints1.gridy = 0;
              constraints1.gridwidth = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(cbName1, constraints1);
              panel1.add(cbName1);
              // setup search combobox (Name and corresponding key)
              cbName1.addItem ("Choose one:");
              cbPersonId1.addItem("0");
              // setup First Name label in display area
              lbFirstName.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.NONE;
              constraints1.gridwidth = 1;
              layout.setConstraints(lbFirstName, constraints1);
              panel1.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName1.setFont(labelFont);
              tfFirstName1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName1, constraints1);
              panel1.add(tfFirstName1);
              // setup Last Name label in display area
              lbLastName.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.NONE;
              layout.setConstraints(lbLastName, constraints1);
              panel1.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName1.setFont(labelFont);
              tfLastName1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 1;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName1, constraints1);
              panel1.add(tfLastName1);
              // setup Address label in display area
              lbAddress.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 2;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbAddress, constraints1);
              panel1.add(lbAddress);
              // setup Address input field in display area
              tfAddress1.setFont(labelFont);
              tfAddress1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 2;
              constraints1.gridwidth = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              constraints1.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfAddress1, constraints1);
              panel1.add(tfAddress1);
              // setup City label in display area
              lbCity.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCity, constraints1);
              panel1.add(lbCity);
              // setup City input field in display area
              tfCity1.setFont(labelFont);
              tfCity1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCity1, constraints1);
              panel1.add(tfCity1);
              // setup State label in display area
              lbState.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbState, constraints1);
              panel1.add(lbState);
              // setup State input field in display area
              tfState1.setFont(labelFont);
              tfState1.setEnabled(false);
              constraints1.gridx = 3;
              constraints1.gridy = 3;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfState1, constraints1);
              panel1.add(tfState1);
              // setup Postcode label in display area
              lbPostcode.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPostcode, constraints1);
              panel1.add(lbPostcode);
              // setup Address input field in display area
              tfPostcode1.setFont(labelFont);
              tfPostcode1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfPostcode1, constraints1);
              panel1.add(tfPostcode1);
              // setup Country label in display area
              lbCountry.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCountry, constraints1);
              panel1.add(lbCountry);
              // setup Country input field in display area
              tfCountry1.setFont(labelFont);
              tfCountry1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 4;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCountry1, constraints1);
              panel1.add(tfCountry1);
              // setup Email Address label in display area
              lbEmailAddress = new JLabel ("Email Address:");
              lbEmailAddress.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbEmailAddress, constraints1);
              panel1.add(lbEmailAddress);
              // setup Email Address input field in display area
              tfEmailAddress1.setFont(labelFont);
              constraints1.gridx = 1;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfEmailAddress1, constraints1);
              panel1.add(tfEmailAddress1);
              // setup Home Phone Number label in display area
              lbHomeNumber.setFont(labelFont);
              constraints1.gridx = 2;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbHomeNumber, constraints1);
              panel1.add(lbHomeNumber);
              // setup Home Phone Number input field in display area
              tfHomeNumber1.setFont(labelFont);
              tfHomeNumber1.setEditable(false);
              constraints1.gridx = 3;
              constraints1.gridy = 5;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfHomeNumber1, constraints1);
              panel1.add(tfHomeNumber1);
              // setup Fax Number label in display area
              lbFaxNumber.setFont(labelFont);
              constraints1.gridx = 0;
              constraints1.gridy = 6;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFaxNumber, constraints1);
              panel1.add(lbFaxNumber);
              // setup Fax Number input field in display area
              tfFaxNumber1.setFont(labelFont);
              tfFaxNumber1.setEditable(false);
              constraints1.gridx = 1;
              constraints1.gridy = 6;
              constraints1.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFaxNumber1, constraints1);
              panel1.add(tfFaxNumber1);
    // indicate inquiry pane
              pane_number = 1;
              // read table get the list of names in CB search key
         accessDBInit();
              // define listener after adding items to CB to avoid triggering it
              cbName1.addItemListener(new ComboBoxHandler());
    //--------------------End showPane1()------------------------------------------->>>
    //--------------------Start showPane2()----------------------------------------->>>
         // Setup screen 2(update and delete pane) including labels, input fields,
         // comboboxes, and buttons. Table PERSONS is read to list inquiry parameters.
         void showPane2(){
              panel2 = new JPanel();
              cbpanel2 = new JPanel();
              labelFont = new Font("Arial",Font.PLAIN,12);
              buttonFont = new Font("Arial",Font.BOLD,12);
              // set screen border
              panel2.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab2, panel2);
              // setup layout as GridBagLayout
              constraints2.insets = new Insets(2,2,2,2);
              panel2.setLayout (layout);
              cbpanel2.setLayout (layout);
              // setup Name combobox label
              lbSelectName.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 0;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbSelectName, constraints2);
              panel1.add(lbSelectName);
              // setup Name combobox as search key
              cbName2.setFont(labelFont);
              constraints2.ipady = 10;
              constraints2.gridx = 1;
              constraints2.gridy = 0;
              constraints2.gridwidth = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(cbName1, constraints2);
              panel1.add (cbName1);
              // setup search combobox (Name and corresponding key)
              cbName1.addItem ("Choose one:");
              cbPersonId1.addItem("0");
              // setup First Name label in display area
              lbFirstName.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.NONE;
              constraints2.gridwidth = 1;
              layout.setConstraints(lbFirstName, constraints2);
              panel1.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName2.setFont(labelFont);
              tfFirstName2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName2, constraints2);
              panel1.add(tfFirstName2);
              // setup Last Name label in display area
              lbLastName.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.NONE;
              layout.setConstraints(lbLastName, constraints2);
              panel1.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName2.setFont(labelFont);
              tfLastName2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 1;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName2, constraints2);
              panel1.add(tfLastName2);
              // setup Address label in display area
              lbAddress.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 2;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbAddress, constraints2);
              panel1.add(lbAddress);
              // setup Address input field in display area
              tfAddress2.setFont(labelFont);
              tfAddress2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 2;
              constraints2.gridwidth = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              constraints2.fill = GridBagConstraints.HORIZONTAL;
              layout.setConstraints(tfAddress2, constraints2);
              panel1.add(tfAddress2);
              // setup City label in display area
              lbCity.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCity, constraints2);
              panel1.add(lbCity);
              // setup City input field in display area
              tfCity2.setFont(labelFont);
              tfCity2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCity2, constraints2);
              panel1.add(tfCity2);
              // setup State label in display area
              lbState.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbState, constraints2);
              panel1.add(lbState);
              // setup State input field in display area
              tfState2.setFont(labelFont);
              tfState2.setEnabled(false);
              constraints2.gridx = 3;
              constraints2.gridy = 3;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfState2, constraints2);
              panel1.add(tfState2);
              // indicate inquiry pane
              pane_number = 1;
              // setup Address label in display area
              lbPostcode.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbPostcode, constraints2);
              panel1.add(lbPostcode);
              // setup Address input field in display area
              tfPostcode2.setFont(labelFont);
              tfPostcode2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfPostcode2, constraints2);
              panel1.add(tfPostcode2);
              // setup Country label in display area
              lbCountry.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbCountry, constraints2);
              panel1.add(lbCountry);
              // setup Country input field in display area
              tfCountry2.setFont(labelFont);
              tfCountry2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 4;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfCountry2, constraints2);
              panel1.add(tfCountry2);
              // setup Email Address label in display area
              lbEmailAddress = new JLabel ("Email Address:");
              lbEmailAddress.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbEmailAddress, constraints2);
              panel1.add(lbEmailAddress);
              // setup Email Address input field in display area
              tfEmailAddress2.setFont(labelFont);
              constraints2.gridx = 1;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfEmailAddress2, constraints2);
              panel1.add(tfEmailAddress2);
              // setup Home Phone Number label in display area
              lbHomeNumber.setFont(labelFont);
              constraints2.gridx = 2;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbHomeNumber, constraints2);
              panel1.add(lbHomeNumber);
              // setup Home Phone Number input field in display area
              tfHomeNumber2.setFont(labelFont);
              tfHomeNumber2.setEditable(false);
              constraints2.gridx = 3;
              constraints2.gridy = 5;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfHomeNumber2, constraints2);
              panel1.add(tfHomeNumber2);
              // setup Fax Number label in display area
              lbFaxNumber.setFont(labelFont);
              constraints2.gridx = 0;
              constraints2.gridy = 6;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFaxNumber, constraints2);
              panel1.add(lbFaxNumber);
              // setup Fax Number input field in display area
              tfFaxNumber2.setFont(labelFont);
              tfFaxNumber2.setEditable(false);
              constraints2.gridx = 1;
              constraints2.gridy = 6;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFaxNumber2, constraints2);
              panel1.add(tfFaxNumber2);
              // setup UPDATE button in display area
              btUpdate.setFont(buttonFont);
              constraints2.gridx = 3;
              constraints2.gridy = 7;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(btUpdate, constraints2);
              panel2.add(btUpdate);
              // setup DELETE button in display area
              btDelete.setFont(buttonFont);
              constraints2.gridx = 1;
              constraints2.gridy = 7;
              constraints2.anchor = GridBagConstraints.WEST;
              layout.setConstraints(btDelete, constraints2);
              panel2.add(btDelete);
              btUpdate.addActionListener(new ButtonHandler());
              btDelete.addActionListener(new ButtonHandler());
              // allow ALT U to press update button
              btUpdate.setMnemonic('u');
              // allow ALT D to press delete button
              btDelete.setMnemonic('d');
              // read table get the list of names in combo box search key
    accessDBInit();
              // define listener after adding items to CB to avoid triggering it
              cbName2.addItemListener(new ComboBoxHandler());
    //--------------------End showPane2()------------------------------------------->>>
    //--------------------Start showPane3()----------------------------------------->>>
         // Setup screen 2(insert pane) including labels, input fields, comboboxes,
         // and buttons.
         void showPane3(){
              panel3      = new JPanel();
              // set screen border
              panel3.setBorder(BorderFactory.createTitledBorder(
                   BorderFactory.createEtchedBorder(),""));
              // add tabbedpane to panel
              tpane.addTab(tab3, panel3);
              // setup layout as GridBagLayout
              constraints3.insets = new Insets(2,2,2,2);
              panel3.setLayout (layout);
              // setup First Name label in display area
              JLabel lbFirstName = new JLabel("First Name:");
              lbFirstName.setFont(labelFont);
              constraints3.gridx = 0;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbFirstName, constraints3);
              panel3.add(lbFirstName);
              // setup First Name input field in display area
              tfFirstName3.setFont(labelFont);
              constraints3.ipady = 8; // adjust heigth of input field
              constraints3.gridx = 1;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfFirstName3, constraints3);
              panel3.add(tfFirstName3);
              // setup Last Name label in display area
              lbLastName = new JLabel("Last Name: ");
              lbLastName.setFont(labelFont);
              constraints3.gridx = 2;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(lbLastName, constraints3);
              panel3.add(lbLastName);
              // setup Last Name input field in display area
              tfLastName3.setFont(labelFont);
              constraints3.gridx = 3;
              constraints3.gridy = 0;
              constraints3.anchor = GridBagConstraints.WEST;
              layout.setConstraints(tfLastName3, constraints3);
              panel3.add(tfLastName3);
              // setup Middle Name label in display area
              lbAddress = new JLabel("Address: ");
              lbAddress.setFont(labelFont);
              constraints3.gridx = 0;
              constraints3.gridy = 1;
              constraints3.anch

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class andy extends JFrame {
      // Define constant variables
      final static String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
      final static String url = "jdbc:odbc:addBKTAFE";
      final static String login = "LOG-IN";
      final static String tab_login = "Log-in";
      final static String tab1 = "INQUIRE Personnel Details";
      final static String tab2 = "UPDATE/DELETE Personnel Details";
      final static String tab3 = "INSERT Personnel Details";
      final static String tab4 = "PRINT";
      final static String insert = "SAVE RECORD";
      final static String update = "UPDATE RECORD";
      final static String delete = "DELETE RECORD";
      final static String inquire = "INQUIRE RECORD";
      final static String clear = " CLEAR ";
      final static String relogin = "Log-in failed! Please relog-in!";
      final static String norecfound = "No Record Found!";
      final static String recinserted = "Record Inserted!";
      final static String recupdated = "Record Updated!";
      final static String recdeleted = "Record Deleted!";
      final static String numericerror = "Age should be numeric!";
      final static String information = "INFORMATION";
      final static String error = "ERROR";
      final static String genexception = "GENERAL EXCEPTION";
      final static String sqlexception = "SQL EXCEPTION";
      final static String confdelete = "CONFIRM DELETE";
      final static String slash = "/";
      final static String table1 = "persons";
      final static String table2 = "Addresses";
      // Define container, panels and tabbedpane
      Container cntr = getContentPane();
      JTabbedPane tpane = new JTabbedPane();
      JPanel cbpanel1 , cbpanel2 , cbpanel3,
             panel1 , panel2 , panel3, panel4;
      // Define fonts to be used
      Font labelFont = new Font("Arial",Font.PLAIN,12);
      Font buttonFont = new Font("Arial",Font.BOLD,13);
      // Define labels
      JLabel lbUser = new JLabel("Enter User ID: " );
      JLabel lbPassword = new JLabel("Enter Password: ");
      JLabel lbSelectName = new JLabel("Search Name: " );
      JLabel lbFirstName = new JLabel("First Name: " );
      JLabel lbLastName = new JLabel("Last Name: " );
      JLabel lbAddress = new JLabel("Address: " );
      JLabel lbCity = new JLabel("City: " );
      JLabel lbState = new JLabel("State: " );
      JLabel lbPostcode = new JLabel("Postcode: " );
      JLabel lbCountry = new JLabel("Country: " );
      JLabel lbEmailAddress = new JLabel("Email Address: " );
      JLabel lbHomeNumber = new JLabel("Home Phone No.: " );
      JLabel lbFaxNumber = new JLabel("Fax No.: " );
      // Define combo boxes in third screen (insert pane)
      JComboBox cbName1     = new JComboBox();
      JComboBox cbName2     = new JComboBox();
      JComboBox cbName3     = new JComboBox();
      JComboBox cbPersonId1 = new JComboBox();
      JComboBox cbPersonId2 = new JComboBox();
      JComboBox cbPersonId3 = new JComboBox();
      // Inquiry fields on first screen (inquiry pane)
      JTextField tfFirstName1 = new JTextField("",30);
      JTextField tfLastName1 = new JTextField("",30);
      JTextField tfAddress1 = new JTextField("",30);
      JTextField tfCity1 = new JTextField("",15);
      JTextField tfState1 = new JTextField("",15);
      JTextField tfPostcode1 = new JTextField("",30);
      JTextField tfCountry1 = new JTextField("",15 );
      JTextField tfEmailAddress1 = new JTextField("",30);
      JTextField tfHomeNumber1 = new JTextField("",15);
      JTextField tfFaxNumber1 = new JTextField("",15 );
      // Input fields on second screen (update/delete pane)
      JTextField tfFirstName2 = new JTextField("",30);
      JTextField tfLastName2 = new JTextField("",30);
      JTextField tfAddress2 = new JTextField("",30);
      JTextField tfCity2 = new JTextField("",15);
      JTextField tfState2 = new JTextField("",15);
      JTextField tfPostcode2 = new JTextField("",30);
      JTextField tfCountry2 = new JTextField("",15);
      JTextField tfEmailAddress2 = new JTextField("",30);
      JTextField tfHomeNumber2 = new JTextField("",15);
      JTextField tfFaxNumber2 = new JTextField("",15);
      // Input fields on third screen (inset details pane)
      JTextField tfFirstName3 = new JTextField("",30);
      JTextField tfLastName3 = new JTextField("",30);
      JTextField tfAddress3 = new JTextField("",30);
      JTextField tfCity3 = new JTextField("",15);
      JTextField tfState3 = new JTextField("",15);
      JTextField tfPostcode3 = new JTextField("",30);
      JTextField tfCountry3 = new JTextField("",15);
      JTextField tfEmailAddress3 = new JTextField("",30);
      JTextField tfHomeNumber3 = new JTextField("",15);
      JTextField tfFaxNumber3 = new JTextField("",15);
      GridBagLayout layout = new GridBagLayout();
      GridBagConstraints constraints = new GridBagConstraints();
      public andy() {
        super("Address Book Application");
        showPane1();
        showPane2();
        showPane3();
        showPane4();
        cntr.add(tpane, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900,385);
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screenSize.width  - getWidth())/2,
                    (screenSize.height - getHeight())/2);
        setVisible(true);
      // Setup screen 1(inquiry pane) including labels, input fields, comboboxes.
      // Table PERSONS is read to list inquiry parameters.
      void showPane1() {
        panel1 = new JPanel();
        cbpanel1 = new JPanel();
        // set screen border
        panel1.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab1, panel1);
        // setup layout as GridBagLayout
        constraints.insets = new Insets(2,2,2,2);
        panel1.setLayout (layout);
        cbpanel1.setLayout (layout);
        // setup Name combobox label
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel1.add(lbSelectName);
        // setup Name combobox as search key
        cbName1.setFont(labelFont);
        constraints.ipady = 10;
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName1, constraints);
        panel1.add(cbName1);
        // setup search combobox (Name and corresponding key)
        cbName1.addItem ("Choose one:");
        cbPersonId1.addItem("0");
        // setup First Name label in display area
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel1.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName1.setFont(labelFont);
        tfFirstName1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName1, constraints);
        panel1.add(tfFirstName1);
        // setup Last Name label in display area
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel1.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName1.setFont(labelFont);
        tfLastName1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName1, constraints);
        panel1.add(tfLastName1);
        // setup Address label in display area
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel1.add(lbAddress);
        // setup Address input field in display area
        tfAddress1.setFont(labelFont);
        tfAddress1.setEditable(false);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress1, constraints);
        panel1.add(tfAddress1);
        // setup City label in display area
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
            layout.setConstraints(lbCity, constraints);
        panel1.add(lbCity);
        // setup City input field in display area
        tfCity1.setFont(labelFont);
        tfCity1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity1, constraints);
        panel1.add(tfCity1);
        // setup State label in display area
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel1.add(lbState);
        // setup State input field in display area
        tfState1.setFont(labelFont);
        tfState1.setEnabled(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState1, constraints);
        panel1.add(tfState1);
        // setup Postcode label in display area
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel1.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode1.setFont(labelFont);
        tfPostcode1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode1, constraints);
        panel1.add(tfPostcode1);
        // setup Country label in display area
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel1.add(lbCountry);
        // setup Country input field in display area
        tfCountry1.setFont(labelFont);
        tfCountry1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry1, constraints);
        panel1.add(tfCountry1);
        // setup Email Address label in display area
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel1.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress1.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress1, constraints);
        panel1.add(tfEmailAddress1);
        // setup Home Phone Number label in display area
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel1.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber1.setFont(labelFont);
        tfHomeNumber1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber1, constraints);
        panel1.add(tfHomeNumber1);
        // setup Fax Number label in display area
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel1.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber1.setFont(labelFont);
        tfFaxNumber1.setEditable(false);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber1, constraints);
        panel1.add(tfFaxNumber1);
        // indicate inquiry pane
        // pane_number = 1;
        // read table get the list of names in CB search key
        // accessDBInit();
        // define listener after adding items to CB to avoid triggering it
        // cbName1.addItemListener(new ComboBoxHandler());
      //--------------------End showPane1()------------------------------------------->>>
      //--------------------Start showPane2()----------------------------------------->>>
      void showPane2() {
        panel2 = new JPanel();
        cbpanel2 = new JPanel();
        // set screen border
        panel2.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab2, panel2);
        // setup layout as GridBagLayout
        constraints.ipady = 0;
        panel2.setLayout (layout);
        cbpanel2.setLayout (layout);
        // setup Name combobox label
        lbSelectName = new JLabel("Search Name: ");
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel2.add(lbSelectName);
        // setup Name combobox as search key
        cbName2.setFont(labelFont);
        constraints.ipady = 10;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName2, constraints);
        panel2.add(cbName2);
        // setup search combobox (Name and corresponding key)
        cbName2.addItem ("Choose one:");
        cbPersonId2.addItem("0");
        // setup UPDATE button in display area
        JButton btUpdate = new JButton("Update");
        btUpdate.setFont(buttonFont);
    //    btUpdate.addActionListener(new ButtonHandler());
        btUpdate.setMnemonic(KeyEvent.VK_U);
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(btUpdate, constraints);
        panel2.add(btUpdate);
        // setup DELETE button in display area
        JButton btDelete = new JButton("Delete");
        btDelete.setFont(buttonFont);
    //    btDelete.addActionListener(new ButtonHandler());
        btDelete.setMnemonic(KeyEvent.VK_D);
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(btDelete, constraints);
        panel2.add(btDelete);
        // setup First Name label in display area
        lbFirstName = new JLabel("First Name: ");
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel2.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName2.setFont(labelFont);
        tfFirstName2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName2, constraints);
        panel2.add(tfFirstName2);
        // setup Last Name label in display area
        lbLastName = new JLabel("Last Name: ");
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel2.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName2.setFont(labelFont);
        tfLastName2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName2, constraints);
        panel2.add(tfLastName2);
        // setup Address label in display area
        lbAddress = new JLabel("Address: ");
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel2.add(lbAddress);
        // setup Address input field in display area
        tfAddress2.setFont(labelFont);
        tfAddress2.setEditable(true);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress2, constraints);
        panel2.add(tfAddress2);
        // setup City label in display area
        lbCity = new JLabel("City: ");
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
        layout.setConstraints(lbCity, constraints);
        panel2.add(lbCity);
        // setup City input field in display area
        tfCity2.setFont(labelFont);
        tfCity2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity2, constraints);
        panel2.add(tfCity2);
        // setup State label in display area
        lbState = new JLabel("State: ");
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel2.add(lbState);
        // setup State input field in display area
        tfState2.setFont(labelFont);
        tfState2.setEnabled(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState2, constraints);
        panel2.add(tfState2);
        // setup Postcode label in display area
        lbPostcode = new JLabel("Postcode: ");
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel2.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode2.setFont(labelFont);
        tfPostcode2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode2, constraints);
        panel2.add(tfPostcode2);
        // setup Country label in display area
        lbCountry = new JLabel("Country: ");
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel2.add(lbCountry);
        // setup Country input field in display area
        tfCountry2.setFont(labelFont);
        tfCountry2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry2, constraints);
        panel2.add(tfCountry2);
        // setup Email Address label in display area
        lbEmailAddress = new JLabel ("Email Address: ");
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel2.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress2.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress2, constraints);
        panel2.add(tfEmailAddress2);
        // setup Home Phone Number label in display area
        lbHomeNumber = new JLabel("Home Phone No.: ");
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel2.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber2.setFont(labelFont);
        tfHomeNumber2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber2, constraints);
        panel2.add(tfHomeNumber2);
        // setup Fax Number label in display area
        lbFaxNumber = new JLabel("Fax No.: ");
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel2.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber2.setFont(labelFont);
        tfFaxNumber2.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber2, constraints);
        panel2.add(tfFaxNumber2);
      //-----------------------------End showpane2()---------------------------------->>
      //--------------------Start showPane3()----------------------------------------->>>
      void showPane3() {
        panel3 = new JPanel();
        // cbpanel3 = new JPanel();
        // set screen border
        panel3.setBorder(BorderFactory.createTitledBorder(
          BorderFactory.createEtchedBorder(),""));
        // add tabbedpane to panel
        tpane.addTab(tab3, panel3);
        // setup layout as GridBagLayout
        panel3.setLayout(layout);
        constraints.ipady = 0;
        panel3.setLayout (layout);
        // cbpanel3.setLayout (layout);
        // setup Name combobox label
        lbSelectName = new JLabel("Search Name: ");
        lbSelectName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbSelectName, constraints);
        panel3.add(lbSelectName);
        // setup Name combobox as search key
        cbName3 = new JComboBox();
        cbName3.setFont(labelFont);
        constraints.ipady = 10;
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(cbName3, constraints);
        panel3.add(cbName3);
        // setup search combobox (Name and corresponding key)
        cbName3.addItem ("Choose one:");
        cbPersonId3.addItem("0");
        // setup INSERT button in display area
        JButton btInsert = new JButton("Insert");
        btInsert.setFont(buttonFont);
    //    btInsert.addActionListener(new ButtonListener());
        btInsert.setMnemonic(KeyEvent.VK_S);
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(btInsert, constraints);
        panel3.add(btInsert);
        // setup CLEAR button in display area
        JButton btClear = new JButton("Clear");
        btClear.setFont(buttonFont);
    //    btClear.addActionListener(new ButtonListener());
        btClear.setMnemonic(KeyEvent.VK_C);
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(btClear, constraints);
        panel3.add(btClear);
        // setup First Name label in display area
        lbFirstName = new JLabel("First Name: ");
        lbFirstName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFirstName, constraints);
        panel3.add(lbFirstName);
        // setup First Name input field in display area
        tfFirstName3.setFont(labelFont);
        tfFirstName3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFirstName3, constraints);
        panel3.add(tfFirstName3);
        // setup Last Name label in display area
        lbLastName = new JLabel("Last Name: ");
        lbLastName.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbLastName, constraints);
        panel3.add(lbLastName);
        // setup Last Name input field in display area
        tfLastName3.setFont(labelFont);
        tfLastName3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfLastName3, constraints);
        panel3.add(tfLastName3);
        // setup Address label in display area
        lbAddress = new JLabel("Address: ");
        lbAddress.setFont(labelFont);
        constraints.gridwidth = 1;
        constraints.anchor = GridBagConstraints.EAST;
        layout.setConstraints(lbAddress, constraints);
        panel3.add(lbAddress);
        // setup Address input field in display area
        tfAddress3.setFont(labelFont);
        tfAddress3.setEditable(true);
        constraints.gridwidth = constraints.REMAINDER;
        constraints.anchor = GridBagConstraints.WEST;
        constraints.weightx = 1.0;
        constraints.fill = GridBagConstraints.HORIZONTAL;
        layout.setConstraints(tfAddress3, constraints);
        panel3.add(tfAddress3);
        // setup City label in display area
        lbCity = new JLabel("City: ");
        lbCity.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        constraints.fill = GridBagConstraints.NONE;
        layout.setConstraints(lbCity, constraints);
        panel3.add(lbCity);
        // setup City input field in display area
        tfCity3.setFont(labelFont);
        tfCity3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfCity3, constraints);
        panel3.add(tfCity3);
        // setup State label in display area
        lbState = new JLabel("State: ");
        lbState.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbState, constraints);
        panel3.add(lbState);
        // setup State input field in display area
        tfState3.setFont(labelFont);
        tfState3.setEnabled(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfState3, constraints);
        panel3.add(tfState3);
        // setup Postcode label in display area
        lbPostcode = new JLabel("Postcode: ");
        lbPostcode.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbPostcode, constraints);
        panel3.add(lbPostcode);
        // setup Address input field in display area
        tfPostcode3.setFont(labelFont);
        tfPostcode3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfPostcode3, constraints);
        panel3.add(tfPostcode3);
        // setup Country label in display area
        lbCountry = new JLabel("Country: ");
        lbCountry.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbCountry, constraints);
        panel3.add(lbCountry);
        // setup Country input field in display area
        tfCountry3.setFont(labelFont);
        tfCountry3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfCountry3, constraints);
        panel3.add(tfCountry3);
        // setup Email Address label in display area
        lbEmailAddress = new JLabel ("Email Address: ");
        lbEmailAddress.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbEmailAddress, constraints);
        panel3.add(lbEmailAddress);
        // setup Email Address input field in display area
        tfEmailAddress3.setFont(labelFont);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfEmailAddress3, constraints);
        panel3.add(tfEmailAddress3);
        // setup Home Phone Number label in display area
        lbHomeNumber = new JLabel("Home Phone No.: ");
        lbHomeNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = constraints.RELATIVE;
        layout.setConstraints(lbHomeNumber, constraints);
        panel3.add(lbHomeNumber);
        // setup Home Phone Number input field in display area
        tfHomeNumber3.setFont(labelFont);
        tfHomeNumber3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        constraints.gridwidth = constraints.REMAINDER;
        layout.setConstraints(tfHomeNumber3, constraints);
        panel3.add(tfHomeNumber3);
        // setup Fax Number label in display area
        lbFaxNumber = new JLabel("Fax No.: ");
        lbFaxNumber.setFont(labelFont);
        constraints.anchor = GridBagConstraints.EAST;
        constraints.gridwidth = 1;
        layout.setConstraints(lbFaxNumber, constraints);
        panel3.add(lbFaxNumber);
        // setup Fax Number input field in display area
        tfFaxNumber3.setFont(labelFont);
        tfFaxNumber3.setEditable(true);
        constraints.anchor = GridBagConstraints.WEST;
        layout.setConstraints(tfFaxNumber3, constraints);
        panel3.add(tfFaxNumber3);
      //-----------------------------End showpane3()---------------------------------->>
      //-----------------------------Start showPane4()-------------------------------->>
      void showPane4() {
    //    qtm = new QueryTableModel();
    //    JTable table = new JTable(qtm);
    //    String query = "SELECT FirstName, LastName, HomePhone, " +
    //                   "FROM Addresses ORDER By LastName";
    //    qtm.setQuery(query);
        JPanel demoPanel = new JPanel();
        demoPanel.setPreferredSize(new Dimension(400,500));
        demoPanel.setBackground(Color.pink);
        demoPanel.add(new JLabel("Demo Panel in place of table",
                                  SwingConstants.CENTER));
        JScrollPane scrollPane = new JScrollPane(demoPanel);
        panel4 = new JPanel();
    //    pane_number = 4;
        panel4.setLayout(layout);
        constraints.ipady = 0;
    //    labelFont = new Font("Arial", Font.PLAIN, 12);   defined above
        buttonFont = new Font("Arial", Font.PLAIN, 13);
       // set screen border
       panel4.setBorder(
         BorderFactory.createTitledBorder(
           BorderFactory.createEtchedBorder(), ""));
       // add panel to tabbed pane
       tpane.addTab(tab4, panel4);
       JLabel lbPrint = new JLabel("Print");
       lbPrint.setFont(labelFont);
       constraints.anchor = constraints.EAST;
       layout.setConstraints(lbPrint, constraints);
       panel4.add(lbPrint);
       JButton btPrint = new JButton("Print");
       btPrint.setFont(buttonFont);
    //   btPrint.addActionListener(new ButtonListener());
       btPrint.setMnemonic(KeyEvent.VK_P);
       constraints.anchor = constraints.WEST;
       constraints.gridwidth = constraints.REMAINDER;
       layout.setConstraints(btPrint, constraints);
       panel4.add(btPrint);
       constraints.weighty = 1.0;
       constraints.fill = constraints.BOTH;
       constraints.anchor = constraints.CENTER;
       layout.setConstraints(scrollPane, constraints);
       panel4.add(scrollPane);
      public static void main(String[] args) {
        new andy();
    }

  • How can I display JTextFields correctly on a JPanel using GridBagLayout?

    I had some inputfields on a JPanel using the boxLayout. All was ok. Then I decided to change the panellayout to GridBagLayout. The JLabel fields are displayed correctly but the JTextField aren't. They are at the JPanel but have a size of 0??? So we cannot see what we type in these fields... Even when I put some text in the field before putting it on the panel.
    How can I display JTextFields correctly on a JPanel using GridBagLayout?
    here is a shortcut of my code:
    private Dimension sFieldSize10 = new Dimension(80, 20);
    // Create and instantiate Selection Fields
    private JLabel lSearchAbrText = new JLabel();
    private JTextField searchAbrText = new JTextField();
    // Set properties for SelectionFields
    lSearchAbrNumber.setText("ABR Number (0-9999999):");
    searchAbrNumber.setText("");
    searchAbrNumber.createToolTip();
    searchAbrNumber.setToolTipText("enter the AbrNumber.");
    searchAbrNumber.setPreferredSize(sFieldSize10);
    searchAbrNumber.setMaximumSize(sFieldSize10);
    public void createViewSubsetPanel() {
    pSubset = new JPanel();
    // Set layout
    pSubset.setLayout(new GridBagLayout());
    GridBagConstraints gbc = new GridBagConstraints();
    // Add Fields
    gbc.gridy = 0;
    gbc.gridx = GridBagConstraints.RELATIVE;
    pSubset.add(lSearchAbrNumber, gbc);
    // also tried inserting this statement
    // searchAbrNumber.setText("0000000");
    // without success
    pSubset.add(searchAbrNumber,gbc);
    pSubset.add(lSearchAbrText, gbc);
    pSubset.add(searchAbrText, gbc);
    gbc.gridy = 1;
    pSubset.add(lSearchClassCode, gbc);
    pSubset.add(searchClassCode, gbc);
    pSubset.add(butSearch, gbc);
    }

    import java.awt.*;
    import java.awt.event.*;
    import javax .swing.*;
    public class GridBagDemo {
      public static void main(String[] args) {
        JLabel
          labelOne   = new JLabel("Label One"),
          labelTwo   = new JLabel("Label Two"),
          labelThree = new JLabel("Label Three"),
          labelFour  = new JLabel("Label Four");
        JLabel[] labels = {
          labelOne, labelTwo, labelThree, labelFour
        JTextField
          tfOne   = new JTextField(),
          tfTwo   = new JTextField(),
          tfThree = new JTextField(),
          tfFour  = new JTextField();
        JTextField[] fields = {
          tfOne, tfTwo, tfThree, tfFour
        Dimension
          labelSize = new Dimension(125,20),
          fieldSize = new Dimension(150,20);
        for(int i = 0; i < labels.length; i++) {
          labels.setPreferredSize(labelSize);
    labels[i].setHorizontalAlignment(JLabel.RIGHT);
    fields[i].setPreferredSize(fieldSize);
    GridBagLayout gridbag = new GridBagLayout();
    JPanel panel = new JPanel(gridbag);
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.weightx = 1.0;
    gbc.weighty = 1.0;
    gbc.insets = new Insets(5,5,5,5);
    panel.add(labelOne, gbc);
    panel.add(tfOne, gbc);
    gbc.gridwidth = gbc.RELATIVE;
    panel.add(labelTwo, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    panel.add(tfTwo, gbc);
    gbc.gridwidth = 1;
    panel.add(labelThree, gbc);
    panel.add(tfThree, gbc);
    gbc.gridwidth = gbc.RELATIVE;
    panel.add(labelFour, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    panel.add(tfFour, gbc);
    final JButton
    smallerButton = new JButton("smaller"),
    biggerButton = new JButton("wider");
    final JFrame f = new JFrame();
    ActionListener l = new ActionListener() {
    final int DELTA_X = 25;
    int oldWidth, newWidth;
    public void actionPerformed(ActionEvent e) {
    JButton button = (JButton)e.getSource();
    oldWidth = f.getSize().width;
    if(button == smallerButton)
    newWidth = oldWidth - DELTA_X;
    if(button == biggerButton)
    newWidth = oldWidth + DELTA_X;
    f.setSize(new Dimension(newWidth, f.getSize().height));
    f.validate();
    smallerButton.addActionListener(l);
    biggerButton.addActionListener(l);
    JPanel southPanel = new JPanel(gridbag);
    gbc.gridwidth = gbc.RELATIVE;
    southPanel.add(smallerButton, gbc);
    gbc.gridwidth = gbc.REMAINDER;
    southPanel.add(biggerButton, gbc);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.getContentPane().add(panel);
    f.getContentPane().add(southPanel, "South");
    f.pack();
    f.setLocation(200,200);
    f.setVisible(true);

  • How can I control the size of a cell in the GridBagLayout?

    Hi,Swing Gurus
    I am developing a swing-based program using JBulider5 enterprise.
    It seems to me that the GridBagLayout is really a hard nut!
    How can I control the size of a cell in the GridBagLayout?
    It seems that I cann't control the size of a cell directly.
    But how the size of a particular cell is determined when I switch the layout manager from XYLayout to GridBagLayout?
    Thx in advance!
    Regards,
    Justine

    hi,i have not done what you are asking but there are fields like
    COLUMNWIDTH, MINSIZE, MAXGRIDSIZE, PREFEREDSIZE to which you can set the appropriate values and test for your need.hope this helped.bye martian.

  • Here is my GridBagLayout version of the code

         public void constructGUI()
               c= getContentPane();
              //Construct the menus and their listeners
              JMenu filemenu = new JMenu("File");
              JMenuItem saveas= new JMenuItem ("Save Amortization As");
              saveas.addActionListener(new ActionListener(){
                   public void actionPerformed (ActionEvent e)
                        JFileChooser filechooser = new JFileChooser ();
                        filechooser.setFileSelectionMode ( JFileChooser.FILES_ONLY);
                        int result = filechooser.showSaveDialog (null);
                        if (result== JFileChooser.CANCEL_OPTION)
                             return;
                        File filename = filechooser.getSelectedFile();
                        if (filename==null||filename.getName().equals (" "))
                             JOptionPane.showMessageDialog( null, "Invalid File Name", "Invalid FileName", JOptionPane.ERROR_MESSAGE );
                        else {
                             try
                                  System.out.println("I am ready to create the streams");
                                  FileOutputStream file = new FileOutputStream(filename, true);
                                  OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file));
                                  String info= "The data is based on"+"\n";
                                  filestream.write(info);
                                  System.out.println("I wrote the first string called info");
                                  String interestdata= "INTEREST:"+" "+interest+"\n";
                                  filestream.write(interestdata);
                                  String timedata="The amortization period is:"+" "+time+"\n";
                                  filestream.write(timedata);
                                  String loandata="The money borrowed is:"+" "+moneyFormat.format(loannumber)+"\n";
                                  filestream.write(loandata);
                                  String totals= "Total of Payments Made:"+" " +moneyFormat.format(totalpayments)+"\n"+"Total Interest Paid:"+"  "+moneyFormat.format(totalinterest)+"\n";
                                  filestream.write(totals);
                                  String filestring = "PAYMENT NUMBER"+"   " + "PAYMENT" + "   " + " PRINCIPLE" + "   " + "INTEREST" +"   " + " BALANCE" + "\n";
                                  filestream.write(filestring);
                                  double loannumberkf= loannumber;
                                  System.out.println(timenumber);
                                  for (int j=1; j<=timenumber ; j++ )
                                       double principlekf=payment-loannumberkf*z;
                                       double balancef=loannumberkf-principlekf;
                                       String display ="\n"+ Integer.toString(j)+"                " + moneyFormat.format(payment)+"        "+ moneyFormat.format(principlekf)+ "     "+moneyFormat.format(loannumberkf*z)+ "     "+ moneyFormat.format(balancef)+"\n";
                                       filestream.write(display);
                                       loannumberkf=loannumberkf-principlekf;
                                  filestream.flush();
                                  file.close();
                             catch ( IOException ioException )
                                  JOptionPane.showMessageDialog (null, "File Does not exist", "Invalid File Name", JOptionPane.ERROR_MESSAGE);
                        }//end of else
                 } //end anonymous inner class
              filemenu.add(saveas);
              JMenuItem exit= new JMenuItem ("Exit");
              exit.addActionListener( new ActionListener() {
                        public void actionPerformed (ActionEvent e)
                             System.exit(0);
                   } //end anonymous inner class
              ); // end call to ActionListener
              filemenu.add(exit);
              JMenuItem summaries=new JMenuItem ("Save Summaries As");
              MenuHandler menuhandler= new MenuHandler();
              summaries.addActionListener(menuhandler);
              filemenu.add(summaries);
              //construct the second JMenu
              JMenu colorchooser=new JMenu("Color Chooser");
              JMenuItem colorchooseritem=new JMenuItem("Choose Color");
              colorchooseritem.addActionListener (new ActionListener() {
                                  public void actionPerformed(ActionEvent e)
                                       color=JColorChooser.showDialog(Mortgagecalculation.this, "Choose a Color", color);
                                       c.setBackground(color);
                                       c.repaint();
                         ); //end of registration
              colorchooser.add(colorchooseritem);
              //third menu
              JMenu service = new JMenu("Services");
              JMenuItem s1= new JMenuItem ("Display Amortization");
              JMenuItem s2= new JMenuItem ("Calender");
              service.add(s1);
              service.add(s2);
              //Create menu bar and add the two JMenu objects
              JMenuBar menubar = new JMenuBar();
              setJMenuBar(menubar);
              menubar.add(filemenu); // end of menu construction
              menubar.add(colorchooser);
              menubar.add(service);
              //set the layout manager for the JFrame
              gbLayout = new GridBagLayout();
              c.setLayout(gbLayout);
              gbConstraints = new GridBagConstraints();
              //construct table and place it on the North part of the Frame
              JLabel tablelabel=new JLabel ("The Table below displays amortization values after you press O.K. on the payments window. Payments window appears after you enter the values for rate, period and loan");
              mydefaulttable = new DefaultTableModel();
                   mydefaulttable.addColumn("PAYMENT NUMBER");
                   mydefaulttable.addColumn ("PAYMENT AMOUNT");
                   mydefaulttable.addColumn ("PRINCIPLE");
                   mydefaulttable.addColumn ("INTEREST");
                   mydefaulttable.addColumn("LOAN BALANCE");
              Box tablebox=Box.createVerticalBox();   
              mytable=new JTable(mydefaulttable);
              tablelabel.setLabelFor(mytable);
              JScrollPane myscrollpane= new JScrollPane (mytable);
              tablebox.add(tablelabel);
              tablebox.add(myscrollpane);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 50;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.NORTH;
              addComponent(tablebox,0,0,3,1,GridBagConstraints.NORTH);
            //c.add (tablebox, BorderLayout.NORTH);
              //create center panel
              JLabel panellabel=new JLabel("Summarries");
              MyPanel panel =new MyPanel();
              panel.setSize (10, 50);
              panel.setBackground(Color.red);
              panellabel.setLabelFor(panel);
              Box panelbox=Box.createVerticalBox();
              panelbox.add(panellabel);
              panelbox.add(panel);
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
            //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.CENTER;
              addComponent(panelbox,1,1,1,1,GridBagConstraints.CENTER);
              //c.add (panelbox, BorderLayout.CENTER);
              //add time in the SOUTH part of the Frame
              Panel southpanel=new Panel();
              southpanel.setBackground(Color.magenta);
              Date time=new Date();
              String timestring=DateFormat.getDateTimeInstance().format(time);
              TextField timefield=new TextField("The Date and Time in Chicago is:"+" "+timestring, 50);
              southpanel.add(timefield);
              //gbConstraints.weightx = 100;
              //gbConstraints.weighty = 1;
              //gbConstraints.fill = GridBagConstraints.HORIZONTAL;
              gbConstraints.anchor = GridBagConstraints.SOUTH;
              addComponent(southpanel,0,2,3,1,GridBagConstraints.SOUTH);
              //c.add(southpanel, BorderLayout.SOUTH);
              //USE "BOX LAYOUT MANAGER" TO ARRANGE COMPONENTS LEFT TO RIGHT WITHIN THE SOUTH PART OF THE FRAME
              //Create a text area to output more information about the application.Place it in a box and place box EAST
              Font f=new Font("Serif", Font.ITALIC+Font.BOLD, 16);
              string="-If you would like to exit this program\n"+
              "-click on the exit menu item \n"+
                   "-if you would like to save the table as a text file \n"+
                   "-click on Save As menu item \n"+"-You can reenter new values for calculation\n"+
                   " as many times as you would like.\n"+
                   "-You can save the summaries also on a different file\n"+
                   "-Files are appended";
              JLabel infolabel= new JLabel ("Information About this Application", JLabel.RIGHT);
              JTextArea textarea=new JTextArea(25,25);
              textarea.setFont(f);
              textarea.append(string);
              infolabel.setLabelFor(textarea);
              Box box =Box.createVerticalBox();
              box.add(infolabel);
              box.add(new JScrollPane (textarea));
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHEAST;
              addComponent(box,2,1,1,1,GridBagConstraints.SOUTHEAST);
              //c.add(box, BorderLayout.EAST);
              //Create the text fields for entering data and place them in a box WEST
              Panel panelwest = new Panel();
              //create the first panelwest and place the text fields in it
              Box box1=Box.createVerticalBox();
              JLabel rate= new JLabel ("Enter Rate", JLabel.RIGHT);
              interestfield=new JTextField ("Enter Interest here and press Enter", 15);
              rate.setLabelFor(interestfield);
              box1.add(rate);
              box1.add(interestfield);
              JLabel period=new JLabel("Enter Amortization Periods", JLabel.RIGHT);
              timenumberfield=new JTextField("Enter amortization period in months and press Enter", 15);
              period.setLabelFor(timenumberfield);
              box1.add(period);
              box1.add(timenumberfield);
              JLabel loan=new JLabel("Enter Present Value of Loan", JLabel.RIGHT);
              loanamountfield =new JTextField ("Enter amount of loan and press Enter", 15);
              loan.setLabelFor(loanamountfield);
              box1.add(loan);
              box1.add(loanamountfield);
              JLabel submit = new JLabel("Press Submit Button to Calculate", JLabel.RIGHT);
              submitbutton= new JButton("SUBMIT");
              submit.setLabelFor(submitbutton);
              box1.add(submit);
              box1.add(submitbutton);
              panelwest.add(box1);
              //Add the panel to the content pane
              //gbConstraints.weightx = 50;
              //gbConstraints.weighty = 100;
              //gbConstraints.fill = GridBagConstraints.BOTH;
              gbConstraints.anchor = GridBagConstraints.SOUTHWEST;
              addComponent(panelwest,0,1,1,1,GridBagConstraints.SOUTHWEST);
              //c.add(panelwest, BorderLayout.WEST);
              //Event handler registration for text fields and submit button
              TextFieldHandler handler=new TextFieldHandler();
              interestfield.addActionListener(handler);
              timenumberfield.addActionListener(handler);
              loanamountfield.addActionListener(handler);
              submitbutton.addActionListener(handler);
              setSize(1000, 700);   
              setVisible(true);
              System.out.println("repainting table, constructor");
              System.out.println("I finished repainting. End of ConstructGUI");
         } // END OF CONSTUCTGUI
         // addComponent() is developed here
         private void addComponent(Component com,int row,int column,int width,int height,int ancor)
              //set gridx and gridy
              gbConstraints.gridx = column;
              gbConstraints.gridy = row;
              //set gridwidth and gridheight
              gbConstraints.gridwidth = width;
              gbConstraints.gridheight = height;
              gbConstraints.anchor = ancor;
              //set constraints
              gbLayout.setConstraints(com,gbConstraints);
              c.add(com);          
         

    Quit cross-posting (in different forums) every time you have a question.
    Quit multi-posting (asking the same questions twice) when you ask a question.
    Start responding to your old questions indicating whether the answers you have been given have been helpfull or not.
    Read the tutorial before asking a question. Start with [url http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html]How to Use GridBag Layout. Of course its the most difficult Layout Manager to master so I would recommend you use various combinations of the other layout managers to achieve your desired results.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • How to see the borders of a "display area" in GridBagLayout

    I would like to see the display area of a JPanel .
    I use this technique:
    panel.setBorder(new TitledBorder(new LineBorder(Color.blue, 2), "DisplayArea?"));
    //Is this correct?
    If not, how can I see the borders of a display area (as opposed to the borders of a JPanel ) of a JPanel ?
    note: I am new to Swing, so I am using the word "display area" in the context of what I read in the API for java.awt.GridBagLayout .
    Maybe there is no real concept of a "display area"?
    I am trying to get the JPanel to expand to the borders of its "display area", but I can't see what is going on. Either I am not expanding the JPanel, or the "display area" is smaller than I would think.
    Thanks.
    Edited by: rikasai on May 3, 2009 2:07 AM

    I think your basic problem lies in this "note: I am new to Swing,",
    and quite probably do not have a sufficient understanding of layoutManagers,
    in particular the one associated with JFrame.
    your problem reads as though you have a JPanel that you have sized to (e.g.) 400,200
    and added this to a JFrame, sized at (e.g.) 600,400, and you expect this to give you a
    100 blank area around the panel.
    the nature of a JFrame's default layoutManager is that if you add something to it,
    via frame.add(panel), it will be added to the default area of the frame (CENTER), and
    it will take all the available space. So, whether you specify 400,200 or 50,50 etc,
    the panel will take up all of the available space in the contentPane of the 600,400 frame.

  • How to control the maximum size of a component in a GridBagLayout

    Here is a small program that demonstrates my issue (it's originally from a big program that I couldn't attach here).
    I have a GridBagLayout with some components in it. Some of the components are JEditorPane (displaying some HTML) within JPanel and are individally scrollable.
    Here we go:
    - when I resize the main panel, every components will resize accordingly to their weight (which is here the same for all of them): fine
    - when I reduce the size of the main panel until it reaches all the preferred size of each component, the scrollPane of the main panel appears so that the user can scroll: not fine
    The behaviour I'm looking for is: when I reduce the size of the main panel, when it reaches the preferred size of the components, I would like that the JEditorPane (which are in JPanel with BorderLayout/CENTER) display their individual scrollbars so that I can see all the JEditor panes at the same time without having to scroll the main window.
    If the user continues to reduce the size of the main panel, then, at one point, display the scrollpane of the main panel.
    See what I mean? How to control this?
    Here is the code:
    @SuppressWarnings("serial")
    public final class CGridBagLayout2 extends JFrame {
         JPanel mainPanel;
         private final JScrollPane scrollPane;
         private JPanel panelize(Component component, String localization) {
              JPanel output = new JPanel(new BorderLayout());          
              output.add(component, localization);
              return output;
        public void addComponentsToMainPanel() {
              mainPanel.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.weightx = 1.0;
              c.fill = GridBagConstraints.BOTH;
              String TEST_BIGTEXT = "<html><body><h2>Path</h2>toto/tutu/tata/TestN<h2>Prerequisites</h2>blah blah blah blah<br/><b>blah blah</b> blah blah\nblah blah <u>blah</u> blahblah blah blah<h2>Description</h2>blah blah blah blah<br/><b>blah blah</b> blah blah\nblah blah <u>blah</u> blahblah blah blah blah\nblah blah blah <br/>lah blah blah <br/>lah blah blah blah blah blah blah blah FIN</body></html>";
              for (int index=0; index<10; index++) {
                   c.gridheight = 5; // nb Testcases for this test
                   c.anchor = GridBagConstraints.FIRST_LINE_START; // align all the components top-left aligned
                   c.gridy = index;
                   JLabel a = new JLabel("AAAAA");
                   c.gridx = 0;
                   mainPanel.add(panelize(a, BorderLayout.NORTH), c);
                   JLabel b = new JLabel("BBBBB");
                   c.gridx = 1;
                   mainPanel.add(panelize(b, BorderLayout.NORTH), c);
                   JEditorPane d = new JEditorPane("text/html", TEST_BIGTEXT);               
                   c.gridx = 2;
                   mainPanel.add(panelize(d, BorderLayout.CENTER), c);
                   JEditorPane e = new JEditorPane("text/html", TEST_BIGTEXT);               
                   c.gridx = 3;
                   mainPanel.add(panelize(e, BorderLayout.CENTER), c);
                   index++;
         public CGridBagLayout2() {
              super("GridBagLayout");
              mainPanel = new JPanel();
              addComponentsToMainPanel();
              scrollPane = new JScrollPane(mainPanel);
              setContentPane(scrollPane);
         public static void main(String[] args) {
              Frame frame;
              WindowListener exitListener;
              exitListener = new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        Window window = e.getWindow();
                        window.setVisible(false);
                        window.dispose();
                        System.exit(0);
              frame = new CGridBagLayout2();
              frame.addWindowListener(exitListener);
              frame.setPreferredSize(new Dimension(1000, 800));
              frame.pack();
              frame.setVisible(true);
    }Many thanks in advance, I'm getting crazy on this one :)

    Ok, thanks for this information, I thought I had seen this happening in the past when embedding a component in the center area of a JPanel with BorderLayout.
    Anyway, as I said I tested with JScrollPane as well and it does not change anything.
    Here is the code modified:
    @SuppressWarnings("serial")
    public final class CGridBagLayout2 extends JFrame {
         JPanel mainPanel;
         private final JScrollPane scrollPane;
         private JPanel panelize(Component component, String localization) {
              JPanel output = new JPanel(new BorderLayout());          
              output.add(component, localization);
              return output;
        public void addComponentsToMainPanel() {
              mainPanel.setLayout(new GridBagLayout());
              GridBagConstraints c = new GridBagConstraints();
              c.weightx = 1.0;
              c.fill = GridBagConstraints.BOTH;
              String TEST_BIGTEXT = "<html><body><h2>Path</h2>toto/tutu/tata/TestN<h2>Prerequisites</h2>blah blah blah blah<br/><b>blah blah</b> blah blah\nblah blah <u>blah</u> blahblah blah blah<h2>Description</h2>blah blah blah blah<br/><b>blah blah</b> blah blah\nblah blah <u>blah</u> blahblah blah blah blah\nblah blah blah <br/>lah blah blah <br/>lah blah blah blah blah blah blah blah FIN</body></html>";
              for (int index=0; index<10; index++) {
                   c.gridheight = 5; // nb Testcases for this test
                   c.anchor = GridBagConstraints.FIRST_LINE_START; // align all the components top-left aligned
                   c.gridy = index;
                   JLabel a = new JLabel("AAAAA");
                   c.gridx = 0;
                   mainPanel.add(panelize(a, BorderLayout.NORTH), c);
                   JLabel b = new JLabel("BBBBB");
                   c.gridx = 1;
                   mainPanel.add(panelize(b, BorderLayout.NORTH), c);
                   JEditorPane d = new JEditorPane("text/html", TEST_BIGTEXT);               
                   c.gridx = 2;
                   mainPanel.add(panelize(new JScrollPane(d), BorderLayout.CENTER), c);
                   JEditorPane e = new JEditorPane("text/html", TEST_BIGTEXT);               
                   c.gridx = 3;
                   mainPanel.add(panelize(new JScrollPane(e), BorderLayout.CENTER), c);
         public CGridBagLayout2() {
              super("GridBagLayout");
              mainPanel = new JPanel();
              addComponentsToMainPanel();
              scrollPane = new JScrollPane(mainPanel);
              setContentPane(scrollPane);
         public static void main(String[] args) {
              Frame frame;
              WindowListener exitListener;
              exitListener = new WindowAdapter() {
                   @Override
                   public void windowClosing(WindowEvent e) {
                        Window window = e.getWindow();
                        window.setVisible(false);
                        window.dispose();
                        System.exit(0);
              frame = new CGridBagLayout2();
              frame.addWindowListener(exitListener);
              frame.setPreferredSize(new Dimension(1000, 800));
              frame.pack();
              frame.setVisible(true);
    }Edited by: eric_gavaldo on Sep 15, 2010 2:18 PM

  • Max. no. of rows in GridbagLayout

    Is there any limit for number of rows (y) in GridbagLayout?
    Recently I mistyped the 'Y' parameters as 888 during creating a GUI. The code compiled smoothly but it gave ArrayIndexOutOfBoundsException: 888 at run time.
    Anybody has some idea about it.
    vinod

    A word of advice; don't post the same question in a number of forums. You have posted it here in three different forums. The folks who will be the most help to you read most of the forums and the extra posting causes a waste of time and bandwidth.<BR><BR>My personal take on your problem is that if you are getting more than 65k rows, Excel is the wrong tool. You are looking at data, not information. The human mind doesn't really work that way, and while you might be getting the number out and be replacing an oldgreenbar report, I'd suggest that you look at what you really want to find out.<BR><BR>When drilling, you are normally looking for exceptions -- best performance and/or worst performance -- and the people who need the information need to know what they are looking for. Doing a report that returns 65K rows is not going to make it easier to manage a business. Think about using ranking, top 5% returns, and possibly some flags in the database to narrow the focus. Also, attribute dimesnions or focussing the drill can help.<BR><BR>I've done various types of decision support, analysis, and Executive Information Systems for over 20 years and I've seen what can be really useful. If a customer asks for a massive report, I try to determine how the information will be used and while it may be easy to give the customer what is requested, I normally also probvide my best estimation of a tool that provides the same information in a much more digestible way, using graphics, exception reporting, and better data orgainzation.<BR><BR>A 65k row drill doesn't really help anyone. There are better ways to get the same type of information.

  • Problem with the GridBagLayout Manager

    Hello i am new to Java Swing and i am facing a problem with the GridBagLayout layout manager . the code in question is attached. First compile and run the code. It will execute w/o probs . Then go to the "Console" tab. There the diff components (6 buttons and 1 text area) are haphazardly arranged where as all measures where taken to prevent it in the code. The GridBagLayout manager for this tab is not working properly please help.
    The code in question:-
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         Container generalContainer; // container for the general pane
         Container consoleContainer; // container for the console pane
         GridBagLayout consoleLayout = new GridBagLayout(); // GridBagLayout for the console
         GridBagConstraints consoleConstraints;// GridBagConstraints for the console
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(700,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
               //for general tab
               FlowLayout layout= new FlowLayout();
               generalContainer = generalPane;
               layout.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layout );
               //for  console tab
               consoleContainer = consolePane;
               consoleConstraints = new GridBagConstraints();
               // *******Finished********
              //********** All buttons text areas are declared here**********
                //*******for the general tab**********
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //******END******
             //*******for the console tab
                 //text area          
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(700,400));
              consoleCode.setAlignmentX(0.0f);
                   //text area complete
                 //*******for the Console tab**********
              JButton consoleCompile = new JButton("Compile Code");
              JButton consoleSimulate = new JButton("Simulate Code");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //***************END****************
         //Adding buttons and text areas to there respective tabs
              // for the general tab
              generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
             generalContainer.add(generalExit);
             //****END****
              // for the console tab          
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleOpen,0,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSave,1,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleConvert,1,2,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCode,1,0,3,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleCompile,2,0,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleSimulate,2,1,1,1);
              consoleConstraints.fill = GridBagConstraints.BOTH;
              addComp(consoleReset,2,2,1,1);
              //****END****
              // adding the tabs
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
              //****END****
         //This method is used to ad the buttons in the GridBagLayout of the Console tab
         private void addComp( Component c,int row,int column,int width,int height)
            // set gridx and gridy
            consoleConstraints.gridx=column;
            consoleConstraints.gridy=row;
            //set gridwidth and grid height
            consoleConstraints.gridwidth=width;
            consoleConstraints.gridheight=height;
            //set constraints
            consoleLayout.setConstraints(c,consoleConstraints);
            consoleContainer.add(c);     
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

    Thanks for the suggestions. I did away with the GridBagLayout Altogether :-D
    and put all the buttons in a seperate JPanel and added that JPanel into the Console tabs container which was using a BorderLayout this time. Take a look
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    public class MainForm extends JFrame{
         JTabbedPane jtp = new JTabbedPane();
         public MainForm()
              super("Welcome to Grey Griffin -- Network Simulator");
              setSize(800,600);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
              JPanel generalPane = new JPanel();
              generalPane.setLayout(new BoxLayout(generalPane, BoxLayout.Y_AXIS));
              JPanel consolePane = new JPanel();
              consolePane.setLayout(new BoxLayout(consolePane, BoxLayout.Y_AXIS));
              JPanel designPane = new JPanel();
              designPane.setLayout(new BoxLayout(designPane, BoxLayout.Y_AXIS));
              JPanel outputPane = new JPanel();
              outputPane.setLayout(new BoxLayout(outputPane, BoxLayout.Y_AXIS));
              //Setting up Layout for all the tabs
              //**for the general tab
               Container generalContainer;
               FlowLayout layoutGeneral= new FlowLayout();
               generalContainer = generalPane;
               layoutGeneral.setAlignment(FlowLayout.CENTER);
               generalContainer.setLayout( layoutGeneral );
               //**for the console tab
                Container consoleContainer;
                consoleContainer = consolePane;
                consoleContainer.setLayout(new BorderLayout() );
               //Creating buttonpanel for adding the buttons
                JPanel buttonPanel1 = new JPanel();
                buttonPanel1.setLayout(new GridLayout(1,3));
                JPanel buttonPanel2 = new JPanel();
                buttonPanel2.setLayout(new GridLayout(1,3));
              // All buttons / text areas / images are declared here
              //**Buttons for the general tab**//
              JButton generalCreate = new JButton("Create a New Network");
              JButton generalOpen = new JButton("Open an Existing Network");
              JButton generalSave = new JButton("Save the Network");
              JButton generalSaveAs = new JButton("Save As..........");
              JButton generalExit = new JButton("Exit");
              //declaring the buttons
              JButton consoleCompile = new JButton("Compile");
              JButton consoleRun = new JButton("Run");
              JButton consoleReset = new JButton("Reset");
              JButton consoleOpen = new JButton("Open script files");
              JButton consoleSave = new JButton("Save script files");
              JButton consoleConvert = new JButton("Convert Script files to graphical form");
              //declares the textarea where the code is written
              JTextArea consoleCode = new JTextArea();
              consoleCode.setEditable(true);
              consoleCode.setMaximumSize(new Dimension(500,600));
              consoleCode.setAlignmentX(0.0f);
              //Adding buttons and text areas to there respective tabs     
              //**Buttons and text pads for the general tab**
                   generalContainer.add(generalCreate);
              generalContainer.add(generalOpen);
              generalContainer.add(generalSave);
              generalContainer.add(generalSaveAs);
                 generalContainer.add(generalExit);
              //adding buttons to the button panel 1
              buttonPanel1.add(consoleOpen);
              buttonPanel1.add(consoleSave);
              buttonPanel1.add(consoleConvert);
              //adding buttons to the button panel2          
              buttonPanel2.add(consoleRun);
              buttonPanel2.add(consoleReset);
              buttonPanel2.add(consoleCompile);
              //adding button panels and textarea
              consoleContainer.add(buttonPanel1,BorderLayout.NORTH);
              consoleContainer.add(consoleCode,BorderLayout.CENTER);
              consoleContainer.add(new JScrollPane(consoleCode));
              consoleContainer.add(buttonPanel2,BorderLayout.SOUTH);
              //adding the tabs          
              jtp.addTab("General",null,generalPane,"Choose General Options");
              jtp.addTab("Design",null,designPane,"Design your own network!!");
              jtp.addTab("Console",null,consolePane,"Type commands in console for designing");
              jtp.addTab("Output",null,outputPane,"View output");
              getContentPane().add(jtp, BorderLayout.CENTER);
         class TabManager implements ItemListener
              Component tab;
              public TabManager(Component tabToManage)
                   tab = tabToManage;
         public void itemStateChanged(ItemEvent ie)
              int index=jtp.indexOfComponent(tab);
             if (index!=-1)
                  jtp.setEnabledAt(index,ie.getStateChange()== ItemEvent.SELECTED);
             MainForm.this.repaint();
    public static void main(String args[])
         MainForm form = new MainForm();
         form.setVisible(true);
    }

  • How do I add a JMenuBar to a GridBagLayout

    Hi All,
    I've got a GridBagLayout on a JFrame and want to add a menu bar to row 0. How do I do that? What I've tried to do is create a JPanel, add the JPanel (menuPanel) to my GridBagLayout in column 0, row 0, width 4 and height of 1. Then add the JMenuBar (bar) to menuPanel. I get the JPanel on the screen because it takes up space, but now File menu.
    Please help.
    // create JPanel
    menuPanel = new JPanel();
    constraints.fill = GridBagConstraints.BOTH;
    constraints.anchor = GridBagConstraints.NORTHWEST;
    constraints.weightx = 0;
    constraints.weighty = 0;     
    addComponent(menuPanel, 0, 0, 4, 1);  // object, row, column, width, height          
    // set up  menu bar
    fileMenu = new JMenu("File");
    fileMenu.setMnemonic('F');
    newSearch = new JMenuItem("New Search");
    newSearch.setMnemonic('N');
    fileMenu.add(newSearch);
    exit = new JMenuItem("Exit");
    exit.setMnemonic('x');
    fileMenu.add(exit);
    bar = new JMenuBar();
    setJMenuBar(bar);
    menuPanel.add(bar);Thanks,
    Karl

    You don't add a MenuBar to the layout, you add directly to the frame using
    setJMenuBar(myMenuBar);HTH,
    Radish21

  • JLabel text hidden behind another component in GridBagLayout

    Hi everyone
    I have looked for an answer to this but come up short so here I am.
    I am using GridBagLayout to position some Jlabels and a JScrollPane
    I have a JLabel in gridx = 0 and gridy = 0 which spans 2 columns
    under that in gridx = 0, gridy = 1 I have a JList inside a JScrollPane
    it only spans the 1 column but fills the entire column.
    next to this in gridx = 1, gridy = 1 I have a JLabel which should fill the rest of the row. It does this but the text is hidden behind the JScrollPane.
    I have tried changing the fill to REMAINING but then the label does not fill the required area.
    Any ideas why this is happening and how to fix it
    my code is
    contents = (JPanel) getContentPane();
    tabbedPane = new JTabbedPane();
    panel = new JPanel();
    panel.setLayout(gridbag);
    //left hand side
    label = new JLabel("Video Database System",JLabel.CENTER);
    gridConstraints.gridx = 0;
    gridConstraints.gridy = 0;
    gridConstraints.gridwidth = 2;
    gridConstraints.weightx = panel.getWidth() * 0.3;
    gridConstraints.weighty = 0.03;
    gridConstraints.anchor = GridBagConstraints.NORTH;
    gridConstraints.fill = GridBagConstraints.BOTH;
    gridbag.setConstraints(label,gridConstraints);
    label.setOpaque(true);
    label.setBackground(Color.blue);
    label.setFont(boldFont);
    panel.add(label);
    //scrolling list
    list = new JList(FileAccess.titleDVD);
    scrollPane = new JScrollPane(list);
    gridConstraints.gridx = 0;
    gridConstraints.gridy = 1;
    gridConstraints.weightx = 0.3;
    gridConstraints.weighty = 0.7;
    gridConstraints.gridheight = 7;
    gridConstraints.anchor = GridBagConstraints.WEST;
    gridConstraints.fill = GridBagConstraints.VERTICAL;
    gridbag.setConstraints(scrollPane,gridConstraints);
    panel.add(scrollPane);
    //labels in the right hand side, this is the label where the text becomes hidden
    label = new JLabel("TITLE",JLabel.LEFT);
    gridConstraints.gridx = 1;
    gridConstraints.gridy = 1;
    gridConstraints.weighty = 0.7;
    gridConstraints.weightx = 0.9;
    gridConstraints.anchor = GridBagConstraints.NORTH;
    gridConstraints.fill = GridBagConstraints.HORIZONTAL;
    gridbag.setConstraints(label,gridConstraints);
    label.setOpaque(true);
    label.setBackground(Color.yellow);
    panel.add(label);
    tabbedPane.add(panel,"Video Information");
    Thanks

    import java.awt.*;
    import javax.swing.*;
    public class hugh extends JFrame {
      public hugh() {
        JPanel tabPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.weightx = 1.0;
        gbc.weighty = 1.0;
        JLabel topLabel = new JLabel("Video Database System", JLabel.CENTER);
        topLabel.setOpaque(true);
        topLabel.setBackground(Color.pink);
        topLabel.setPreferredSize(new Dimension(275,20));
        gbc.gridwidth = 2;
        tabPanel.add(topLabel, gbc);
        JPanel scrollPanel = new JPanel();
        scrollPanel.setBackground(Color.red);
        scrollPanel.setPreferredSize(new Dimension(375,300));
        scrollPanel.add(new JLabel("JList goes here . . ."));
        JScrollPane scrollPane = new JScrollPane(scrollPanel);
        scrollPane.setPreferredSize(new Dimension(200,300));
        gbc.gridy = 1;
        gbc.gridwidth = gbc.RELATIVE;
        tabPanel.add(scrollPane, gbc);
        JLabel sideLabel = new JLabel("TITLE", JLabel.CENTER);
        sideLabel.setOpaque(true);
        sideLabel.setBackground(Color.pink);
        sideLabel.setPreferredSize(new Dimension(75,20));
        gbc.gridwidth = gbc.REMAINDER;
        tabPanel.add(sideLabel, gbc);
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("Video Information", tabPanel);
        getContentPane().add(tabbedPane);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(400,400);
        setLocation(400,300);
        setVisible(true);
      public static void main(String[] args) {
        new hugh();
    }

  • Using GridBagLayout to fill the full width of a JFrame, ...

    I have two quick questions regarding GridBagLayout.
    1st, I would like the fill the full width of a JFrame with a JPanel. I have tried:
    JFrame frame = new JFrame();
    //Set width and height of frame
    JPanel panel = createFilledPanel();
    panelConstraints.gridx = 0;
    panelConstraints.gridy = 0;
    panelConstraints.fill = GridBagConstraints.HORIZONTAL;But this fails to stretch the panel to the full width of the frame.
    2nd, I would like to align the elements in a panel to the farthest left they can go. I have tried:
    element.anchor = GridBagConstraints.LINE_START;But this aligns all the elements I do this to, to the same starting position horizontally, but not all the way left.
    I would appreciate help with either or both of these questions!

    weightx or weighty : Easy way to understand is priority amongs components and if this componets get setting
    with weightx = 1.0 then this components 's width and height values are respected to be kept over others.
    It just says that, putting the weight on this components over others. kept all others attributes of this componets first
    over other components.
    I hope my jebrish explanation help -

  • GridbagLayout - how to get the size of a gridbag cell?

    Hi,
    i'd like to create a swing widget that automatically rescales the labels inside according to its cell size.
    Therefore i had the idea to get the cell size and set the font size according to this size ( subtracting some inset )
    finally it should look like that:
    |     title text    |
    |   val1  |  val2   |
    |   val3  |  val4   |
    -----------------------the title needs to span 2 cells horizontal,
    the values (valx) span 1 cell
    by resizing the mainPanel, the labels should also resize according to their available space.
    i use this code by now for setting up the widget.
    // title label
    GridBagConstraints gBC_title = new GridBagConstraints();
    jl_title.setFont(titleFont);
    gBC_title.gridx = 0;
    gBC_title.gridy = 0;
    gBC_title.gridwidth = 2; // grid spanning
    gBC_title.weightx = 1;
    gBC_title.weighty = 0.2;
    gBC_title.anchor = GridBagConstraints.CENTER;
    gBC_title.fill = GridBagConstraints.BOTH;              
    mainPanel.add(jl_title, gBC_title); 
    //one of the value labels
    GridBagConstraints gBC_v1 = new GridBagConstraints();
    jl_val1.setFont(valueFont);
    gBC_v1.weightx = 0.5;
    gBC_v1.weighty = 0.4;
    gBC_v1.gridx = 0;
    gBC_v1.gridy = 1;
    gBC_v1.anchor = GridBagConstraints.LINE_END;
    gBC_v1.fill = GridBagConstraints.BOTH;     
    mainPanel.add(jl_val1, gBC_v1);
    (...) The mainPanel is the panel with the Gridbaglayout.
    by resizing the widget i call this method:
    public void adjustFontSize(JLabel label){
                    int adjustedFontSize;
         int inset = 2; // space surrounding the label
         int parentHeight = label.getHeight();     
         int parentWidth = label.getWidth();
    //     System.out.println("available space for  "+label.getText()+": "+ parentWidth +"*"+ parentHeight);     
         if (parentHeight <= parentWidth){
              adjustedFontSize = parentHeight - inset;
         } else {
              adjustedFontSize = parentWidth - inset;
         label.setFont(new Font(null, Font.BOLD, adjustedFontSize));
         System.out.println("adjusting font size for "+label.getText()+": "+adjustedFontSize);
    }//end adjustFontSizethe problem is, that the resizing doesn't really work.
    any ideas?
    the best thing would be to get the parent cell size of the label to resize, and set the font size to allmost this value
    , but i am not able to get the cell size to adjust the label or font size:
    thanks for your help
    Edited by: Sniezn on Mar 12, 2010 1:05 AM

    To make this function properly, you may need to create your own layout manager or do something even more hackish.Here's something more hackish. But first, setting GBC anchor with fill=BOTH doesn't have any effect as the component is resized to fill its cell, so might as well be anchored at all the four corners. Also, there's no need to create a new GBC instance for adding each component.
    Is this the layout you were looking for?import java.awt.*;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.font.FontRenderContext;
    import java.awt.geom.Rectangle2D;
    import javax.swing.*;
    public class ZoomLabelTest {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
          @Override
          public void run() {
            new ZoomLabelTest().makeUI();
      public void makeUI() {
        JLabel labelTitle = new ZoomLabel("title text");
        labelTitle.setHorizontalAlignment(JLabel.CENTER);
        JLabel labelVal1 = new ZoomLabel("val1");
        labelVal1.setHorizontalAlignment(JLabel.RIGHT);
        JLabel labelVal2 = new ZoomLabel("val2");
        JLabel labelVal3 = new ZoomLabel("val3");
        labelVal3.setHorizontalAlignment(JLabel.RIGHT);
        JLabel labelVal4 = new ZoomLabel("val4");
        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.BOTH;
        gbc.gridwidth = 2;
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 1;
        gbc.weighty = 0.2;
        panel.add(labelTitle, gbc);
        gbc.gridwidth = 1;
        gbc.weightx = 0.5;
        gbc.weighty = 0.4;
        gbc.gridy = 1;
        panel.add(labelVal1, gbc);
        gbc.gridx = 1;
        panel.add(labelVal2, gbc);
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(labelVal3, gbc);
        gbc.gridx = 1;
        panel.add(labelVal4, gbc);
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setContentPane(panel);
        frame.setVisible(true);
    class ZoomLabel extends JLabel {
      ComponentListener listener = new ZoomListener();
      public ZoomLabel(String text) {
        super(text);
        addComponentListener(listener);
      private class ZoomListener extends ComponentAdapter {
        @Override
        public void componentResized(ComponentEvent e) {
          // doesn't make a difference for GBL but does for some
          // other layouts, notably BorderLayout
          setPreferredSize(getSize());
          Insets insets = getInsets();
          Font font = getFont();
          int width = getWidth() - insets.left - insets.right;
          int height = getHeight() - insets.top - insets.bottom;
          boolean increased = false;
          boolean decreased = false;
          do {
            Rectangle2D textRect = font.getStringBounds(getText(),
                    new FontRenderContext(null, true, false));
            int textWidth = (int) textRect.getWidth();
            int textHeight = (int) textRect.getHeight();
            if (textWidth > width || textHeight > height) {
              font = font.deriveFont((float) font.getSize() - 1);
              if (increased) {
                break;
              decreased = true;
            } else {
              if (decreased) {
                break;
              font = font.deriveFont((float) font.getSize() + 1);
              increased = true;
          } while (true);
          setFont(font);
    }db
    PS Now somebody tell me that it's not a good idea to setPreferredSize in componentResized ... along with an alternative that's clean(er) ;-)
    edit No, that needs a lot more work to be stable with GBL (or maybe it never will be). It appears to be stable only with the same weightx / weighty for all columns/rows.
    Edited by: DarrylBurke

  • Set minimum size for GridBagLayout

    Hi all,
    I have a dialog which using GridBagLayout. I spent quite a lot of time to test, but still got the following problems. Could anyone give me some solutions?
    1. How do I set the dialog to have a minimum size ?
    Since the dialog is sizeable, so I have to make this limitation to prevent the dialog being too small .
    I tried the following code:
            this.getContentPane().setMinimumSize(new Dimension(686,520));
            this.setMinimumSize(new Dimension(686,520));but it's still not work... , I can still resize it too small.. any other way ?
    2. How do I set its default size when dialog pop up?
    I don't know why the dialog always auto popup in maximum size.
    I have tried to use this.setSize(new Dimension(686, 536)); inside jbInit() function, but still not work...
    Please help ... Thanks a lot.

    Why dont you try this.setResizable(false);?
    Anyway I have given a sample program here using Gridbag layout and this dialog cannot be resized.
    import java.awt.BorderLayout;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class SunExample28 extends JDialog {
         public SunExample28() {
              setTitle("JDialog with Fixed size");
              JLabel nameLbl = new JLabel("Name:");
              JLabel ageLbl = new JLabel("Age:");
              JTextField nameFld = new JTextField(10);
              JTextField ageFld = new JTextField(10);
              GridBagConstraints gbc = new GridBagConstraints();
              Insets in = new Insets(5,5,5,5);
              JPanel compPanel = new JPanel(new GridBagLayout());
              gbc.gridx = 0;
              gbc.gridy = 0;
              compPanel.add(nameLbl,gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 0;
              compPanel.add(nameFld, gbc);
              gbc.insets = in;
              gbc.gridx = 0;
              gbc.gridy = 1;
              compPanel.add(ageLbl, gbc);
              gbc.insets = in;
              gbc.gridx = 1;
              gbc.gridy = 1;
              compPanel.add(ageFld, gbc);
              JButton okBtn = new JButton("OK");
              JButton cancelBtn = new JButton("Cancel");
              JPanel btnPanel = new JPanel();
              btnPanel.add(okBtn);
              btnPanel.add(cancelBtn);
              getContentPane().add(compPanel, BorderLayout.CENTER);
              getContentPane().add(btnPanel, BorderLayout.PAGE_END);
              setDefaultCloseOperation(DISPOSE_ON_CLOSE);
              setSize(500,300);
              setResizable(false);
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              new SunExample28().setVisible(true);
    }

Maybe you are looking for