View RSS Feed

fatabass

A Simple GridLayout Example

Rating: 1 votes, 1.00 average.
by , 12-29-2011 at 12:12 AM (8281 Views)
Java Code:
package myPackage;

import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class GridLayoutFrame extends JFrame implements ActionListener
{
	
	private JButton[] buttons; // array of buttons
	private static final String[] names = {"one", "two", "three"
		,"four","five","six"};
	private boolean toggle = true;
	private Container container;
	private GridLayout gridLayout1;
	private GridLayout gridLayout2;
	
	public GridLayoutFrame()
	{
		super ( "GridLayout Demo" );
		gridLayout1 = new GridLayout(2,3,5,5); // 2 by 3; gaps of 5
		gridLayout2 = new GridLayout(3,2); // 3 by 2; no gaps
		container = getContentPane(); // get content pane
		container.setLayout ( gridLayout1 ); // set JFrame layout
		buttons = new JButton [names.length]; // create array of JButtons
		
		for ( int count = 0; count < names.length ; count++ )
		{
			buttons [ count ] = new JButton ( names[count] );
			buttons [ count ].addActionListener(this);
			add ( buttons[ count ]);			
		}
	}

	public void actionPerformed(ActionEvent e) 
	{
		if ( toggle )
			container.setLayout(gridLayout2);
		else
			container.setLayout(gridLayout1);
		toggle = !toggle;
		container.validate();
	}
}
Java Code:
package myPackage;

import javax.swing.JFrame;

public class TestClass 
{

	public static void main(String[] args) 
	{
		GridLayoutFrame myFrame = new GridLayoutFrame();
		myFrame.setSize(500,500);
		myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		myFrame.setVisible(true);
	}

}

Submit "A Simple GridLayout Example" to Facebook Submit "A Simple GridLayout Example" to Digg Submit "A Simple GridLayout Example" to del.icio.us Submit "A Simple GridLayout Example" to StumbleUpon Submit "A Simple GridLayout Example" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments