?
Solved

Java GridLayout:

Posted on 2009-04-23
43
Medium Priority
?
557 Views
Last Modified: 2012-05-06
Dear Experts:

I have a grid layout as seen below.
The first row of textfields are in  Gridlayout of BorderLayout.North.

The next two rows of textfields are in GridLayout of BorderLayout.Center.

The first two rows have a subheading of the rows. I used  TitledBorder.

I wonder whether there is a way to a subheading to the third row too.

Thanks!
5-digit.png
0
Comment
Question by:duta
  • 18
  • 11
  • 9
  • +1
43 Comments
 

Author Comment

by:duta
ID: 24222095
I would like to place a third subheading where "password" is.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24222102
You would need to nest the layout in CENTER. Use another Container in there
0
 
LVL 92

Expert Comment

by:objects
ID: 24222115
no, you'll need to split it into two 1 row panels for that, same as you have done with the top row

Instead of a BorderLayout for the container try a 1x3 GridLayout

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:duta
ID: 24222227
The layout I have in mind is as seen in the screen shot below:



layout.png
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24222240
The best way to do that is to make a single component class for the first three rows and add three instances together with a button panel to a BoxLayout. Avoid GridLayout - it's ugly without tweaking
0
 

Author Comment

by:duta
ID: 24222252
Genius, you said: to make a single component class for the first three rows and add three instances together with a button panel to a BoxLayout.


  I just  wonder whether you may kindly show me how to that.

Thanks!
0
 

Author Comment

by:duta
ID: 24222259
Is it possible to nest a BorderLayout in BorderLayout.Center?

0
 
LVL 92

Assisted Solution

by:objects
objects earned 400 total points
ID: 24222270
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(row1);
panel.add(row2);
panel.add(row3);

where row1-n are your (GridLayout) rows with a tiutle border

then add panel to CENTER of the main panel
and your button panel to the south

0
 
LVL 92

Expert Comment

by:objects
ID: 24222276
> Is it possible to nest a BorderLayout in BorderLayout.Center?

it is, but don't think you'll need to in your case

0
 

Author Comment

by:duta
ID: 24222355
Savant, you said:
JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(row1);
panel.add(row2);
panel.add(row3);

Row 1, 2, 3 each  needs to contain five textfield cells.

I do not know how to add five textfields cells in a row to the panel.
I am assigning a value to each of the textfields by using an array.

Thanks a lot!
0
 
LVL 92

Expert Comment

by:objects
ID: 24222374
JPanel row = new JPanel(new GridLayout(1, 5));
for (int i=0; i<5; i++) {
  row.add(tf[i]);
}

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24222405
Try something like:
import javax.swing.*;
 
public class InputPanel extends JPanel {
    private JTextField[] fields;
    final int NUM_FIELDS = 5;
 
    public InputPanel(String caption) {
	setBorder(BorderFactory.createTitledBorder(caption));
	fields = new JTextField[NUM_FIELDS];
	for(int i = 0;i < NUM_FIELDS;i++) {	
	    fields[i] = new JTextField(5);
	    add(fields[i]);
	}
    }
 
    public void setField(String text, int index) {
	fields[index].setText(text);
    }
    public String getField(int index) {
	return fields[index].getText();
    }
}

Open in new window

0
 
LVL 26

Expert Comment

by:ksivananth
ID: 24222421
you can achieve by setting GridLayout for all, for e.g.,

1. Create three panels setting Gridlayout with 1 row and 5 cols. add the text fileds.
2. Set TitledBorder to all these panel.
3. Set the GridLayout with 3 rows and 1 col for parent panel/container.
4. add the titled panels to this parent container.
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 800 total points
ID: 24222452
If you run the following it will give you the three input panels
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
 
 
public class F extends JFrame {
 
	private void setGui() {
		try {
			setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
			Container cp = getContentPane();
			cp.setLayout(new BoxLayout(cp, BoxLayout.PAGE_AXIS));
			cp.add(new InputPanel("Last-5-Digit"));
			cp.add(new InputPanel("PIN Number"));
			cp.add(new InputPanel("Password"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
	public static void main(String[] args) {
		try {
			SwingUtilities.invokeAndWait(new Runnable() {
					public void run() {
						F f = new F();
						f.setGui();
						f.setSize(400, 200);
						f.setVisible(true);
					}
				});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
 
 
}

Open in new window

0
 

Author Comment

by:duta
ID: 24222461
Sage, can you kindly give me a made-up code to execute your tip?

I am total beginner.

Thanks!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24222523
Together with a final button panel, the gui looks like this on my system:
gui.png
0
 

Author Comment

by:duta
ID: 24222794
Genius, thank you so much for your kind tip.

I will try your kind tip and come back to you soon.
0
 
LVL 92

Expert Comment

by:objects
ID: 24222805
Thats just what I had already posted, glad you like it :)
Let me know if you need anything different

0
 

Author Comment

by:duta
ID: 24222870
While trying Savant's code, I got  the following error message:


.java:16: 312 cannot find symbol
symbol  : class InputPanel
0
 

Author Comment

by:duta
ID: 24222874
I got it. I have to put class InputPanel.
0
 
LVL 92

Expert Comment

by:objects
ID: 24222882
Its made what I suggested a bit more complicated than need to be. Keeping it simple will save you extra in the long run. I'll let the others finish writing it for you, just remember who suggested it :)
Give me a yell if you need my help.

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24222969
duta, just in case you've been confused by other comments, you're  working with my suggestion made at http:#24222240  ;-)
0
 

Author Comment

by:duta
ID: 24222970
Savant, you kindly gave me the following codes in two occasions to create a table that I posted above.

I have three rows of textfields which need to be placed in a GridLayou (3, 1).
You used one GridLayout (3,1) and another GridLayout (1, 5).

Is the GirdLayout (1,5) nested in the GridLayout (3,1)?

If so, how to nest it?

Thanks



I do not know how to incorporate them

JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(row1);
panel.add(row2);
panel.add(row3);


Panel row = new JPanel(new GridLayout(1, 5));
for (int i=0; i<5; i++) {
  row.add(tf[i]);
}
0
 
LVL 92

Expert Comment

by:objects
ID: 24223156
Panel row1 = new JPanel(new GridLayout(1, 5));
for (int i=0; i<5; i++) {
  row1.add(tf[i]);
}

// now do the same for row2 and row3
// you could use a factory method for that

JPanel panel = new JPanel(new GridLayout(3, 1));
panel.add(row1);
panel.add(row2);
panel.add(row3);

container.add(BorderLayout.CENTER, panel);
container.add(BorderLayout.SOUTH, buttonpanel);


0
 

Author Comment

by:duta
ID: 24223250
Savant, can you explain the following code?

row1.add(tf[i]);

What is  tf [ i ] ?

I need to assign a number to each of the textfields using an array.

Thanks!
0
 
LVL 92

Expert Comment

by:objects
ID: 24223262
they are your textfields, main idea is you use a separate panel for each row which allows you to add a title border to each as you require

0
 

Author Comment

by:duta
ID: 24223684

I ran the following code. But the output (as seen in attached image)  has a little problem.

The textfield starts at a wrong place.

_____________________  current code _______________________

 Container cp = getContentPane();
         
           
      JPanel   row1  =  new  JPanel (  new GridLayout ( 1,  5 ) );
     
      JPanel   row2  =  new  JPanel (  new GridLayout ( 1,  5 ) );
      JPanel   row3  =  new  JPanel (  new GridLayout ( 1,  5 ) );
   
      JPanel   panelC  =  new  JPanel (  new GridLayout ( 3,  1 ) );
           
     
      panelC.add ( row1 );
      panelC.add ( row2 );
      panelC.add ( row3 );
   
      cp.add    (BorderLayout.CENTER, panelC);
   
panelcenter.png
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24223737
What was wrong with the display i posted for you?
0
 

Author Comment

by:duta
ID: 24223757
Genius, I am a real novice. I am a little scared to try a little lengthy code.

I will make sure to try your kind tip.

I do apologize to you for not trying your tip sooner.

Thanks a lot!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 24223759
try this,

import java.awt.Container;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.TitledBorder;

public class TestGridLayout{
      
      private void buildComponent(){
            JFrame frame = new JFrame( "Test GridLayout!" );
            Container cp = frame.getContentPane();
            JPanel row1 = new JPanel( new GridLayout( 1, 5 ) );
            
            JPanel row2 = new JPanel( new GridLayout( 1, 5 ) );
            JPanel row3 = new JPanel( new GridLayout( 1, 5 ) );
            
            JPanel panelC = new JPanel( new GridLayout( 3, 1 ) );
            
            row1.setBorder( new TitledBorder( "Last 5 Digit" ) ) ;
            row2.setBorder( new TitledBorder( "Pin Number" ) ) ;
            row3.setBorder( new TitledBorder( "Password" ) ) ;
            addTextFields( row1 ) ;
            addTextFields( row2 ) ;
            addTextFields( row3 ) ;
            
            panelC.add( row1 );
            panelC.add( row2 );
            panelC.add( row3 );
            
            cp.add( panelC );
            
//            frame.pack() ;
            frame.setSize( 400, 300 ) ;
            frame.setVisible( true ) ;
      }
      
      private void addTextFields( JPanel pnl ){
            for( int i = 0; i < 5; i++ ){
                  pnl.add( new JTextField( 1 ) ) ;
            }
      }
      
      public static void main( String[] args ){
            SwingUtilities.invokeLater( new Runnable(){
                  public void run(){
                        new TestGridLayout().buildComponent() ;
                  }
            }) ;
      }
      
}
0
 
LVL 92

Expert Comment

by:objects
ID: 24223834
make sure your gui leaves enough space to display all your fields.

0
 

Author Comment

by:duta
ID: 24223889
Sage,  I have one quick question.

I need  two more row below the above three rows. The fourth row needs to contain three buttons.

The fifth and last row needs contain labels.

I just wonder whether you may kindly modify the code so that I may have two more rows.

Thanks!
0
 
LVL 26

Assisted Solution

by:ksivananth
ksivananth earned 800 total points
ID: 24224081
check this,

public class TestGridLayout{
      
      private void buildComponent(){
            JFrame frame = new JFrame( "Test GridLayout!" );
            Container cp = frame.getContentPane();
            JPanel row1 = new JPanel( new GridLayout( 1, 5 ) );
            JPanel row2 = new JPanel( new GridLayout( 1, 5 ) );
            JPanel row3 = new JPanel( new GridLayout( 1, 5 ) );
            JPanel row4 = new JPanel( new GridLayout( 1, 3 ) );
            JPanel row5 = new JPanel( new GridLayout( 1, 5 ) );
            
            JPanel panelC = new JPanel( new GridLayout( 5, 1 ) );
            
            row1.setBorder( new TitledBorder( "Last 5 Digit" ) ) ;
            row2.setBorder( new TitledBorder( "Pin Number" ) ) ;
            row3.setBorder( new TitledBorder( "Password" ) ) ;
            addTextFields( row1 ) ;
            addTextFields( row2 ) ;
            addTextFields( row3 ) ;
            addButtons( row4 ) ;
            addLabels( row5 ) ;
            
            panelC.add( row1 );
            panelC.add( row2 );
            panelC.add( row3 );
            panelC.add( row4 );
            panelC.add( row5 );
            
            cp.add( panelC );
            
//            frame.pack() ;
            frame.setSize( 400, 300 ) ;
            frame.setVisible( true ) ;
      }
      
      private void addTextFields( JPanel pnl ){
            for( int i = 0; i < 5; i++ ){
                  pnl.add( new JTextField( 1 ) ) ;
            }
      }
      
      private void addButtons( JPanel pnl ){
            for( int i = 0; i < 3; i++ ){
                  pnl.add( new JButton( "Button - " + i ) ) ;
            }
      }
      
      private void addLabels( JPanel pnl ){
            for( int i = 0; i < 5; i++ ){
                  pnl.add( new JLabel( "Label - " + i ) ) ;
            }
      }
      
      /**
       * @param args
       */
      public static void main( String[] args ){
            // TODO Auto-generated method stub
            SwingUtilities.invokeLater( new Runnable(){
                  public void run(){
                        new TestGridLayout().buildComponent() ;
                  }
            }) ;
      }
      
}
0
 

Author Comment

by:duta
ID: 24224294
Sage, I got  two error messages:

1.  cannot find symbol:   class JButton

2.  cannot find symbol:  class JLabel



Thanks a lot!
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 24224334
you need to import them in the top!

import javax.swing.JButton;
import javax.swing.JLabel;
0
 

Author Comment

by:duta
ID: 24224781
Sage, thank you so much for your kind tip.

I just wonder whether I may ask you one FINAL  quick question.

Is there any way to make the buttons smaller (as sketched by red  lines) so that
there are some space between the buttons and  margin from the border of the panel?

Thanks!
buttons.png
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24225014
As i mentioned earlier, GridLayout produces ugly components if it gets the chance. In this case, the easiest way to fix it would be to set the preferred size for each button
0
 

Author Comment

by:duta
ID: 24225080
Genius, can you kindly show me how to set preferred size in the above code?

Thanks a lot!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24225155
Actually that won't work when i think about it again, but i already showed you how to produce proper looking buttons
0
 
LVL 26

Expert Comment

by:ksivananth
ID: 24225219
just replace your row4 with below,

            JPanel row4 = new JPanel( new FlowLayout( FlowLayout.CENTER, 30, 10 ));
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24225294
Yes, use a FlowLayout as i did. In fact the following should suffice
JPanel row4 = new JPanel();

Open in new window

0
 

Author Closing Comment

by:duta
ID: 31574114
Thank you so much for your extraordinarily patient, kind help!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24228049
:-)
0

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

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

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This video teaches viewers about errors in exception handling.
Suggested Courses
Course of the Month13 days, 19 hours left to enroll

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question