Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 616
  • Last Modified:

GridBagLayout

Please advice how to specify in GridBagLayout one line text boxes with different width.
At the moment I use simple GridLayout, but it split panel eventually and some small text use unnecessary big area.
How to define sizes for each box, so I'll have them in one line but with different sizes.
Thank you
0
gbcbr
Asked:
gbcbr
  • 28
  • 12
  • 11
  • +1
5 Solutions
 
ksivananthCommented:
hope this helps u undertand gbl,

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * TYPE DESCRIPTION HERE
 *
 */
public class TestGridbaglayout{
      
      private JPanel buildComponent(){
            JPanel pnlMain = new JPanel( new GridBagLayout() ) ;
            
            //30%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 0, 1, 1, 0.3, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //70%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 1, 0, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //None - only component display area
            pnlMain.add( new JButton( "Button 3" ), new GridBagConstraints( 2, 0, 1, 1, 0.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            
            //50%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 1, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //50%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 1, 1, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //None - only component display area
            pnlMain.add( new JButton( "Button 3" ), new GridBagConstraints( 2, 1, 1, 1, 0.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            
            
            //~35%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 2, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //~30%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 1, 2, 1, 1, 0.3, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //~35%
            pnlMain.add( new JButton( "Button 3" ), new GridBagConstraints( 2, 2, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            
            //~35%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 3, 1, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //~30%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 1, 3, 2, 1, 0.3, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );

            
            //~35%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 4, 2, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //~30%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 2, 4, 1, 1, 0.3, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            
            //~35%
            pnlMain.add( new JButton( "Button 1" ), new GridBagConstraints( 0, 5, 2, 1, 1.0, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 0, 0, 0, 0 ), 0, 0 ) );
            //~30%
            pnlMain.add( new JButton( "Button 2" ), new GridBagConstraints( 2, 5, 1, 1, 0.3, 0.0,
                    GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets( 0, 0, 0, 0 ), 0, 0 ) );

            return pnlMain ;
      }
      
      /**
       * @param args
       */
      public static void main( String[] args ){
            TestGridbaglayout test = new TestGridbaglayout() ;
        JFrame frame = new JFrame("TestGridbaglayout");
       
        frame.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {System.exit(0);}
        });
 
        frame.getContentPane().add( test.buildComponent(), BorderLayout.CENTER);
        frame.setSize( 400, 400 ) ;
//        frame.pack();
        frame.setVisible(true);
      }
      
}
0
 
gbcbrAuthor Commented:
Thank you for this sample it's very nice, and will help me for future.
But now I need to place 15 boxes in one line with FIXED, permanent width.
Can you provide sample for this case please?
0
 
ksivananthCommented:
Use FlowLayout and specify the sixe for the text field in its constructor, for e.g.

new JTextFeild( 10 ) ;
new JTextFeild( 20 ) ;
0
Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
gbcbrAuthor Commented:
Can you please provide sample for this code:
jPanel1.setBounds(new Rectangle(10, 30, 1260, 30));
        jPanel1.setSize(new Dimension(1260, 30));
        jPanel1.setLayout(new GridLayout(1, 15));

        jLabel1.setText("EUR/USD");
        jLabel1.setForeground(new Color(0, 0, 165));
        jLabel1.setFont(new Font("Lucida Grande", 1, 14));

        jToggleButton1.setText("SELL");
        jToggleButton1.setBackground(Color.red);
        jToggleButton1.setOpaque(true);
        jToggleButton1.setFont(new Font("Lucida Grande", 1, 14));
        jToggleButton1.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jToggleButton1.setBounds(new Rectangle(87, 0, 57, 30));
        jToggleButton1.setToolTipText("SELL");
        jToggleButton1.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    try {
                        jToggleButton1_mouseClicked(e);
                    } catch (Exception f) {
                        f.printStackTrace();
                    }
                }
            });

        jToggleButton2.setText("BUY");
        jToggleButton2.setBackground(Color.red);
        jToggleButton2.setOpaque(true);
        jToggleButton2.setFont(new Font("Lucida Grande", 1, 14));
        jToggleButton2.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
        jToggleButton2.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    try {
                        jToggleButton2_mouseClicked(e);
                    } catch (Exception f) {
                        f.printStackTrace();
                    }
                }
            });


        jTextField1.setBounds(new Rectangle(265, 0, 80, 30));
        jTextField1.setSize(new Dimension(80, 30));
        jTextField1.setHorizontalAlignment(JTextField.CENTER);


        jTextField1.setEditable(false);
        jTextField2.setBounds(new Rectangle(355, 0, 80, 30));
        jTextField2.setSize(new Dimension(80, 30));
        jTextField2.setHorizontalAlignment(JTextField.CENTER);

        jTextField2.setEditable(false);
        jTextField3.setBounds(new Rectangle(450, 0, 80, 30));
        jTextField3.setSize(new Dimension(80, 30));
        jTextField3.setBackground(new Color(181, 255, 181));
        jTextField3.setHorizontalAlignment(JTextField.CENTER);
        jTextField3.setText("1.38624");

        jTextField4.setBounds(new Rectangle(535, 0, 80, 30));
        jTextField4.setSize(new Dimension(80, 30));
        jTextField4.setHorizontalAlignment(JTextField.CENTER);

        jTextField4.setEditable(false);
        jTextField5.setBounds(new Rectangle(620, 0, 80, 30));
        jTextField5.setSize(new Dimension(80, 30));
        jTextField5.setHorizontalAlignment(JTextField.CENTER);

        jTextField5.setEditable(false);
        jTextField6.setBounds(new Rectangle(705, 0, 80, 30));
        jTextField6.setSize(new Dimension(80, 30));
        jTextField6.setBackground(new Color(255, 132, 132));
        jTextField6.setHorizontalAlignment(JTextField.CENTER);
        jTextField6.setText("1.35200");

        jTextField7.setBounds(new Rectangle(790, 0, 80, 30));
        jTextField7.setSize(new Dimension(80, 30));
        jTextField7.setHorizontalAlignment(JTextField.CENTER);
        jTextField7.setText("3");

        jTextField8.setBounds(new Rectangle(875, 0, 80, 30));
        jTextField8.setSize(new Dimension(80, 30));
        jTextField8.setHorizontalAlignment(JTextField.CENTER);
        jTextField8.setText("300");

Open in new window

0
 
CEHJCommented:
I usually use my own mini-framework for this. Is this the sort of thing you mean? (java -jar form-maker.jar)

http://technojeeves.com/tech/form-maker.jar
0
 
gbcbrAuthor Commented:
@CEHJ Thanks you but this is different case.
I try all layouts, but now I'm sure that the best solution for me is this GridBagLayout.
I need advice because for me little bit complicated how to define exact size for each element.
0
 
CEHJCommented:
Well what i have uses a GridBagLayout actually
0
 
ksivananthCommented:
if you don't worry abt resizing,

>>jPanel1.setLayout(new GridLayout(1, 15));

change it to

jPanel1.setLayout(null);
0
 
gbcbrAuthor Commented:
I tried it, no good.
Too much work with low appearance.
Simple Grid Layout much better, but I want improve it and use place better.
0
 
ksivananthCommented:
>>I tried it, no good.

you need to adjust the bounds and size... you'll have to do same type of work with gbl... but gbl offers flexi positioning when resize happens whcih you seem don't want!
0
 
gbcbrAuthor Commented:
I have 10 similar panels 15 elements each, so I have recreate 150 elements manually, and if I need to make some changes I have to do it from zero.
This is the reason why I want to make template of GBL layout and apply it to all 10 panels in the frame. And when I need to make changes, I just change a layout.
0
 
objectsCommented:
A straight FlowLayout should achieve that (you just need to make sure parent panel is wide enough)
0
 
gbcbrAuthor Commented:
I can't find in Class FlowLayout how to set dimentions of elements in FlowLayout, just setHgap, setAlingment.
0
 
objectsCommented:
you set the (preferred) size of the elements being added, and the FlowLayout will use them
0
 
gbcbrAuthor Commented:
@objects
Can you provide please sample based on my code, so I can reproduce it.
0
 
objectsCommented:
JPanel panel = new JPanel(new FlowLayout());
panel.add(new JTextField(20));
panel.add(new JTextField(50));
panel.add(new JTextField(30));
0
 
gbcbrAuthor Commented:
>>panel.add(new JTextField(20))
what is 20?
0
 
objectsCommented:
just specifies size of the field
0
 
gbcbrAuthor Commented:
means horizontal size, what about vertical size?
0
 
objectsCommented:
you can use setPreferredSize()

field.setPreferredSize(new Dimension(width, height));
0
 
CEHJCommented:
If you want to use a GridBagLayout, try something like the following:


import java.awt.*;
import java.awt.event.*;

import java.io.*;

import java.util.*;

import javax.swing.*;


public class F extends JFrame {
    private void setGui() {
	Container cp = getContentPane();
	cp.add(new FieldsPanel());
    }

    public static void main(String[] args) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                    public void run() {
                        F f = new F();
                        f.setGui();
                        f.setSize(200, 200);
                        f.setVisible(true);
                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private class FieldsPanel extends JPanel {
        final int NUM_FIELDS = 15;
        JTextField[] fields = new JTextField[NUM_FIELDS];

        public FieldsPanel() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

            Container cp = getContentPane();
            cp.setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridy = 0;
            gbc.fill = GridBagConstraints.HORIZONTAL;
            gbc.weightx = 1;

            for (int i = 0; i < NUM_FIELDS; i++) {
                gbc.gridx = i;
                fields[i] = new JTextField(10);
                cp.add(fields[i], gbc);
            }
        }
    }
}

Open in new window

0
 
gbcbrAuthor Commented:
@CEHJ
But I don't see any specification for each field. It will be even again.
0
 
objectsCommented:
Just tested FlowLayout, and it works fine
0
 
gbcbrAuthor Commented:
@objects
nothing works. I can't set anything.
private JTextField jTextField1 = new JTextField(80);
    private JTextField jTextField2 = new JTextField(80);
    private JTextField jTextField3 = new JTextField(60);
    private JTextField jTextField4 = new JTextField(80);
    private JTextField jTextField5 = new JTextField(80);
    private JTextField jTextField6 = new JTextField(60);
............
private void jbInit() throws Exception {
........
this.getContentPane().add(jPanel1, null);
..............
jPanel1.add(jTextField1, null);
................
        jPanel1.setBounds(new Rectangle(10, 30, 1260, 30));
        jPanel1.setSize(new Dimension(1260, 30));
        jPanel1.setLayout(new FlowLayout());
..................
        jTextField1.setBounds(new Rectangle(265, 0, 80, 30));
        jTextField1.setSize(new Dimension(80, 30));
        jTextField1.setHorizontalAlignment(JTextField.CENTER);
        jTextField1.setEditable(false);

Open in new window

DCC5.tiff
0
 
CEHJCommented:
>>But I don't see any specification for each field. It will be even again.

Sorry - missed that you didn't want them even
0
 
objectsCommented:
       jPanel1.setBounds(new Rectangle(10, 30, 1260, 30));
        jPanel1.setSize(new Dimension(1260, 30));

remove those (if a layout manager is used by the content pane)


        jTextField1.setBounds(new Rectangle(265, 0, 80, 30));
        jTextField1.setSize(new Dimension(80, 30));

replace that with setPreferredSize as I explained above


        jTextField1.setPreferredSize(new Dimension(80, 30));
0
 
CEHJCommented:
Of course i used an array as a form of shorthand, but to show they can be different widths,  you can do instead:
for (int i = 0; i < NUM_FIELDS; i++) {
                gbc.gridx = i;
		int wid = 0;
		if (i % 4 == 0) {
		    wid = 15;
		    gbc.weightx = 2;
		}
		else {
		    wid = 10;
		    gbc.weightx = 1;
		}
                fields[i] = new JTextField(wid);
                cp.add(fields[i], gbc);
            }

Open in new window

0
 
gbcbrAuthor Commented:
@CEHJ Too complicated for me, sorry.

@objects I'll try tomorrow and post the result. Looks easy, hope it will work for me
0
 
objectsCommented:
yes, keep it simple :)
0
 
CEHJCommented:
>>@CEHJ Too complicated for me, sorry.

Well - the question was about how to use a GridBagLayout -

>>Please advice how to specify in GridBagLayout one line text boxes with different width.

so i showed you
0
 
gbcbrAuthor Commented:
@CEHJ
With same result you can show map of Moon. I will never be there. You know my level, so when I see something overcomplicated for me, I just block my brain from overload.
I need light and easy understandable advice, I'm not from CERN.
Otherwise it has to be ready solution, like OHLC from for_yan, copy-paste and I don't care what is inside and how it works, I just add my parameters and see only perfect result.
0
 
gbcbrAuthor Commented:
This FlowLayout quite understandable for me, but in view that it's already created huge class of 2500 lines, it's also not so easy to reorganize it step by step. This reason I asked about GBL.
But if it is not simple solution for this layout, I will need to make donkey job step by step.
0
 
CEHJCommented:
>>it's already created huge class of 2500 lines

It might be worth attaching that sourc file
0
 
gbcbrAuthor Commented:
what you mean?
0
 
objectsCommented:
you don't need to attach the source :)
0
 
gbcbrAuthor Commented:
I don't attach anything, first of all I don't understand what to that to attach and secondary< work now like coal miner for this changes one by one, looks like I'll arrange it, but for sure not today.
0
 
gbcbrAuthor Commented:
OK, let's say I go from my GridLayout not to GBL to FlowLayout. How I can set different gaps between elements? My main problem is to avoid self elements organizing, I want to do it manually, as a size as a gaps between them. How I can do it in FlowLayout?
0
 
ksivananthCommented:
public FlowLayout(int align, int hgap, int vgap) this will help u to specify the gaps, the size you can pass it to the control constructors as I mentioned earlier!
0
 
gbcbrAuthor Commented:
but it will define all hgaps, but I need individual.
>>My main problem is to avoid self elements organizing, I want to do it manually,
So, I need, in some cases change standard hgap between only two selected elements, and another two, so I can design my view, don't look like army, everything the same.
0
 
ksivananthCommented:
then you need to go with gbl!
0
 
CEHJCommented:
>>I want to do it manually, as a size as a gaps between them. How I can do it in FlowLayout?

You can't. You'd need to be using something like a BoxLayout to do that?
0
 
gbcbrAuthor Commented:
So, we come back to my original question.
May somebody help me please?
0
 
ksivananthCommented:
or play with multiple panel, for e.g.,

JPanel main = new JPanel( new FlowLayout( 10, 10 ) ) ;
JPanel sub1 = new JPanel( 20, 20 ) ;
JPanel sub2 = new JPanel( 10, 20 ) ;
main.add( sub1 ) ;
main.add( sub2 ) ;

whatever copnents added under sub1 will have a space of 20, 20...
0
 
gbcbrAuthor Commented:
This what I have now, I start to redesign it from first line, because I need to add more components in each row.
Each row is a JPanel.
Any advises? Just bear in mind that this is not final construction, maybe tomorrow I'll need to add 1, 2, 3  elements for each row, so I will not redraw everything, just add. DCC6.tiff
0
 
ksivananthCommented:
>>Each row is a JPanel

what I said is multiplt panel in each row!
0
 
gbcbrAuthor Commented:
Yes, each row is one JPanel, so I need organize elements in one row inside my panel, but I want as I said before - organize, don't follow self-organizing.
For example, I want to make gap between JLable EUR/USD and Toggle button SELL 15 or 20px,
how I can do this?
0
 
ksivananthCommented:
>>Yes, each row is one JPanel

I said, multiple panel in each row. you may want to write some test program!
0
 
gbcbrAuthor Commented:
You advice to split my row-panel to sub-panels?
0
 
ksivananthCommented:
check this sample,

import java.awt.FlowLayout;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

/**
 * TYPE DESCRIPTION HERE
 *
 */
public class TestFlowLayout{
      
      public void buildComponents( JPanel pnlRow ){
            JPanel pnl1 = new JPanel( new FlowLayout( FlowLayout.CENTER, 5, 5 ) ) ;
            JPanel pnl2 = new JPanel( new FlowLayout( FlowLayout.CENTER, 20, 20 ) ) ;
            JPanel pnl3 = new JPanel( new FlowLayout( FlowLayout.CENTER, 15, 15 ) ) ;
            JPanel pnl4 = new JPanel( new FlowLayout( FlowLayout.CENTER, 35, 15 ) ) ;
            
            for( int i = 0; i < 3; i++ ){
                  pnl1.add( new JTextField( 3 * ( i + 1 ) ) ) ;
                  pnl2.add( new JTextField( 3 * ( i + 1 ) ) ) ;
                  pnl3.add( new JTextField( 3 * ( i + 1 ) ) ) ;
            }
            
            pnl4.add( new JTextField( 20 ) ) ;
            
            pnlRow.add( pnl1 ) ;
            pnlRow.add( pnl2 ) ;
            pnlRow.add( pnl3 ) ;
            pnlRow.add( pnl4 ) ;
      }
      
      /**
       * @param args
       */
      public static void main( String[] args ){
            TestFlowLayout test = new TestFlowLayout() ;
            
            JFrame frame = new JFrame() ;
            JPanel pnlMain = new JPanel( new GridLayout( 3, 0 ) ) ;
            for( int i = 0; i < 3; i++ ){
                  JPanel pnlRow = new JPanel() ;
                  test.buildComponents( pnlRow ) ;
                  pnlMain.add( pnlRow ) ;
            }
            
            frame.getContentPane().add( pnlMain ) ;
            frame.pack() ;
            frame.setVisible( true ) ;
      }
      
}
0
 
gbcbrAuthor Commented:
Looks nice, but how to adopt it to me case
0
 
ksivananthCommented:
whats the issue now?
0
 
gbcbrAuthor Commented:
I see 10 field on each row, but I don't see any parameters which create them.
0
 
gbcbrAuthor Commented:
I don't need just picture, I need practical solution.
0
 
objectsCommented:
> but it will define all hgaps, but I need individual.

you can control individual gaps with a border
though looking at the image the gaps appear all the same
0
 
gbcbrAuthor Commented:
@objects
any sample?
0
 
objectsCommented:
which part of the layout are stuk on exactly. looking at the image you posted all the textfields in the table are evenly spaced so you could use a GridLayout (or even a JTable)
0
 
gbcbrAuthor Commented:
Yes, at the moment it's a GridLayout.
At first line I try to change it, so small text fields don't share the same area like big one and use for this a FlowLayout.
Generally it looks better and take less area, but I'm also want to group them by adding little more space between groups.
Let's say, first I want move JLabel at the beginning  by adding 20 pixels out of first JToggleButton, and add few pixels between 3 and 4 JTextFields to better visualization etc.
This reason why I ask about a JPanel layout in which I can locate each item in exact position, like I can locate JPanel inside JFrame.
0
 
objectsCommented:
you're not going to achieve it with a single layout, you need to use next panels with different layout managers to manage the various area.

Perhaps a BorderLayout as the top level
with labels and sell/buy buttons(?) in the WEST
header in the NORTH
and the bulk of the textfields in the center using a GridLayout
0
 
gbcbrAuthor Commented:
Thank you for everybody, I'll use all your advises to improve my picture.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 28
  • 12
  • 11
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now