Layout Help

Need help putting a GridLayout within a BorderLayout

Page 1 of 1

2 Replies - 753 Views - Last Post: 21 March 2010 - 01:31 PM Rate Topic: -----

#1 Cancos   User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 66
  • Joined: 04-February 09

Layout Help

Posted 21 March 2010 - 11:37 AM

import javax.swing.*;
import java.awt.*;


public class CalPanel extends JPanel
{
	JButton buttons[];
	JPanel ButtonPanel;
	String names[] = {"+","-","*","/","7","8","9","8","4","5","6","5","1","2","3","2"};
	CalPanel()
	{
		ButtonPanel = new JPanel();
		setLayout(new BorderLayout());
		buttons = new JButton[names.length];
		ButtonPanel.setLayout( new GridLayout(4,4) );

		for(int counter = 0; counter < names.length; counter++)
		{
			buttons[counter] = new JButton(names[counter]);
			ButtonPanel.add(buttons[counter]);
		}
	}
}


So far this is all I have since I've been messing with it for the past 30 minutes. Im new at Java and help would be appreciated. I started out with a GridLayout normally and the buttons appeared fine, but once I tried adding another JPanel for my BorderLayout, nothing appeared. Thanks in advanced!

Is This A Good Question/Topic? 0
  • +

Replies To: Layout Help

#2 Cancos   User is offline

  • D.I.C Head

Reputation: 8
  • View blog
  • Posts: 66
  • Joined: 04-February 09

Re: Layout Help

Posted 21 March 2010 - 11:47 AM

I think I just figured it out! =)
Was This Post Helpful? 0
  • +
  • -

#3 zim1985   User is offline

  • Grand Inquisitor
  • member icon

Reputation: 75
  • View blog
  • Posts: 568
  • Joined: 19-February 10

Re: Layout Help

Posted 21 March 2010 - 01:31 PM

Just to make sure. Make your first JPanel BorderLayout. Then make a second JPanel GridBagLayout. Once you have made your GridBagLayout panel, add it to the first panel.

import javax.swing.*;
import java.awt.*;


public class CalPanel extends JPanel
{
        JButton buttons[];
        JPanel ButtonPanel;
        String names[] = {"+","-","*","/","7","8","9","8","4","5","6","5","1","2","3","2"};
        CalPanel()
        {
                ButtonPanel = new JPanel();
                this.setLayout(new BorderLayout());
                buttons = new JButton[names.length];
                ButtonPanel.setLayout( new GridLayout(4,4) );

                for(int counter = 0; counter < names.length; counter++)
                {
                        buttons[counter] = new JButton(names[counter]);
                        ButtonPanel.add(buttons[counter]);
                }
                this.add(ButtonPanel, BorderLayout.CENTER);
        }
}


That should work...though you can always change the border layout location of the ButtonPanel. Also, calls to "this" make it more specific as to which panel is being called.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1