• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 572
  • Last Modified:

Java GridLayout:

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
duta
Asked:
duta
  • 18
  • 11
  • 9
  • +1
3 Solutions
 
dutaAuthor Commented:
I would like to place a third subheading where "password" is.

0
 
CEHJCommented:
You would need to nest the layout in CENTER. Use another Container in there
0
 
objectsCommented:
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
Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
dutaAuthor Commented:
The layout I have in mind is as seen in the screen shot below:



layout.png
0
 
CEHJCommented:
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
 
dutaAuthor Commented:
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
 
dutaAuthor Commented:
Is it possible to nest a BorderLayout in BorderLayout.Center?

0
 
objectsCommented:
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
 
objectsCommented:
> Is it possible to nest a BorderLayout in BorderLayout.Center?

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

0
 
dutaAuthor Commented:
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
 
objectsCommented:
JPanel row = new JPanel(new GridLayout(1, 5));
for (int i=0; i<5; i++) {
  row.add(tf[i]);
}

0
 
CEHJCommented:
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
 
ksivananthCommented:
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
 
CEHJCommented:
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
 
dutaAuthor Commented:
Sage, can you kindly give me a made-up code to execute your tip?

I am total beginner.

Thanks!
0
 
CEHJCommented:
Together with a final button panel, the gui looks like this on my system:
gui.png
0
 
dutaAuthor Commented:
Genius, thank you so much for your kind tip.

I will try your kind tip and come back to you soon.
0
 
objectsCommented:
Thats just what I had already posted, glad you like it :)
Let me know if you need anything different

0
 
dutaAuthor Commented:
While trying Savant's code, I got  the following error message:


.java:16: 312 cannot find symbol
symbol  : class InputPanel
0
 
dutaAuthor Commented:
I got it. I have to put class InputPanel.
0
 
objectsCommented:
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
 
CEHJCommented:
duta, just in case you've been confused by other comments, you're  working with my suggestion made at http:#24222240  ;-)
0
 
dutaAuthor Commented:
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
 
objectsCommented:
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
 
dutaAuthor Commented:
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
 
objectsCommented:
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
 
dutaAuthor Commented:

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
 
CEHJCommented:
What was wrong with the display i posted for you?
0
 
dutaAuthor Commented:
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
 
ksivananthCommented:
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
 
objectsCommented:
make sure your gui leaves enough space to display all your fields.

0
 
dutaAuthor Commented:
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
 
ksivananthCommented:
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
 
dutaAuthor Commented:
Sage, I got  two error messages:

1.  cannot find symbol:   class JButton

2.  cannot find symbol:  class JLabel



Thanks a lot!
0
 
ksivananthCommented:
you need to import them in the top!

import javax.swing.JButton;
import javax.swing.JLabel;
0
 
dutaAuthor Commented:
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
 
CEHJCommented:
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
 
dutaAuthor Commented:
Genius, can you kindly show me how to set preferred size in the above code?

Thanks a lot!
0
 
CEHJCommented:
Actually that won't work when i think about it again, but i already showed you how to produce proper looking buttons
0
 
ksivananthCommented:
just replace your row4 with below,

            JPanel row4 = new JPanel( new FlowLayout( FlowLayout.CENTER, 30, 10 ));
0
 
CEHJCommented:
Yes, use a FlowLayout as i did. In fact the following should suffice
JPanel row4 = new JPanel();

Open in new window

0
 
dutaAuthor Commented:
Thank you so much for your extraordinarily patient, kind help!
0
 
CEHJCommented:
:-)
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

Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

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