Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java programming articles and tips. Please take your copy here.

Take your copy of free "Java Technology Screensaver"!.

Easy Java Lecture 17: Layout managers - a visual guide part III

JavaFAQ Home » Java Lectures by Anatoliy Malyarenko Go to all tips in Java Lectures by Anatoliy Malyarenko


Bookmark and Share

Part 3, Part II , Part I is here

How to use CardLayout

Here's a snapshot of an application that uses a CardLayout to switch between two panels.

how to use cardLayout demo picture how to use cardLayout demo picture


The CardLayout class helps you manage two or more components (usually JPanel instances) that share the same display space. When using CardLayout, you need to provide a way to let the user choose between the components. CardLayoutDemo uses a combo box for this purpose.

An easier but less flexible way to accomplish the same task is to use a tabbed pane. Here's a picture of a tabbed pane version of the preceding example:

Because a tabbed pane provides its own GUI, using a tabbed pane is simpler than using CardLayout.

Conceptually, each component a CardLayout manages is like a playing card or trading card in a stack, where only the top card is visible at any time. You can choose the card that's showing in any of the following ways:

  • By asking for either the first or last card, in the order it was added to the container.
  • By flipping through the deck backwards or forwards.
  • By specifying a card with a specific name. This is the scheme CardLayoutDemo uses.

The following code from CardLayoutDemo.java creates the CardLayout and the components it manages.

Code:


//Where instance variables are declared:
JPanel cards;
final static String BUTTONPANEL = "JPanel with JButtons";
final static String TEXTPANEL = "JPanel with JTextField";
//Where the components controlled by the CardLayout are
//initialised. Create the "cards".
JPanel card1 = new JPanel();
...
JPanel card2 = new JPanel();
...
//Create the panel that contains the "cards".
cards = new JPanel(new CardLayout());
cards.add(card1, BUTTONPANEL);
cards.add(card2, TEXTPANEL);

When you add a component to a container that a CardLayout manages, you must specify a string that identifies the component being added. For example, in this example, the first panel has the string "JPanel with JButtons", and the second panel has the string"JPanel with JTextField". In this example, those strings are also used in the combo box.

To choose which component a CardLayout shows, you need some additional code. Here's how the example program does this:

Code:


//Where the GUI is assembled:
//Put the JComboBox in a JPanel to get a nicer look.
JPanel comboBoxPane = new JPanel();
//use FlowLayout String
comboBoxItems[] = { BUTTONPANEL, TEXTPANEL };
JComboBox cb = new JComboBox(comboBoxItems);
cb.setEditable(false);
cb.addItemListener(this);
comboBoxPane.add(cb);
...
pane.add(comboBoxPane, BorderLayout.PAGE_START);
pane.add(cards, BorderLayout.CENTER);
...
public void itemStateChanged(ItemEvent evt) {
    CardLayout cl = (CardLayout)(cards.getLayout());
    cl.show(cards, (String)evt.getItem());
}


This example shows that you can use the CardLayout show method to set the currently showing component. The first argument to the show method is the container the CardLayout controls -- that is, the container of the components the CardLayout manages. The second argument is the string that identifies the component to show. This string is the same as was used when adding the component to the container.

How to use FlowLayout

The FlowLayout class provides a very simple layout manager that is used, by default, by JPanels. Here's a picture of an example that uses a flow layout:

FlowLayout puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, FlowLayout uses multiple rows. If the container is wider than necessary for a row of components, the row is, by default, centred horizontally within the container. You can specify that it stick to the left or right side instead by using a FlowLayout constructor that takes an alignment argument. You can also specify how much vertical or horizontal padding is put around the components.

Below is the code from FlowLayoutDemo.java that creates the FlowLayout and the components it manages.

Code:


contentPane.setLayout(new FlowLayout());
contentPane.add(new JButton("Button 1"));
contentPane.add(new JButton("Button 2"));
contentPane.add(new JButton("Button 3"));
contentPane.add(new JButton("Long-Named Button 4"));
contentPane.add(new JButton("5"));

How to use GridBagLayout

Here's a picture of an example that uses GridBagLayout.

how to use gridbaglayout


GridBagLayout is one of the most flexible -- and complex -- layout managers the Java platform provides. A GridBagLayout places components in a grid of rows and columns, allowing specified components to span multiple rows or columns. Not all rows necessarily have the same height. Similarly, not all columns necessarily have the same width. Essentially, GridBagLayout places components in rectangles (cells) in a grid, and then uses the components' preferred sizes to determine how big the cells should be.

The following figure shows the grid for the preceding applet. As you can see, the grid has three rows and three columns. The button in the second row spans all the columns; the button in the third row spans the two right columns.

The way the program specifies the size and position characteristics of its components is by specifying constraints for each component, To specify constraints, you set instance variables in a GridBagConstraints object and tell the GridBagLayout (with the setConstraints method) to associate the constraints with the component.

GridBagLayout was contributed to Javasoft by a programmer who wanted to support the Java effort. It was intended as a proof that the Swing offered enough features for programmers to write their own layout managers. It wasn't designed with human factors and ease of use in mind. If it bothers you (it bothers me) then just don't use it.

How to use GridLayout

Here's a snapshot of an application that uses a GridLayout.

A GridLayout places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize the GridLayoutDemo window, you'll see that the GridLayout changes the cell size so that the cells are as large as possible, given the space available to the container.

Below is the code that creates the GridLayout and the components it manages.

Code:

pane.setLayout(new GridLayout(0,2));
pane.add(new JButton("Button 1"));
pane.add(new JButton("Button 2"));
pane.add(new JButton("Button 3"));
pane.add(new JButton("Long-Named Button 4"));
pane.add(new JButton("5"));

The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary.

Exercise

The RGBColorChooser applet (in the folder RGB) lets the user set the red, green, and blue levels in a colour by manipulating sliders. Something like this could make a useful custom component. Such a component could be included in a program to allow the user to specify a drawing colour, for example. Rewrite the RGBColorChooser as a component.

Make it a subclass of JPanel instead of JApplet. Instead of doing the initialisation in an init() method, you'll have to do it in a constructor. The component should have a method, getColor(), that returns the colour currently displayed on the component. It should also have a method, setColor(Color c), to set the colour to a specified value. Both these methods would be useful to a program that uses your component.

In order to write the setColor(Color c) method, you need to know that if c is a variable of type Color, then c.getRed() is a function that returns an integer in the range 0 to 255 that gives the red level of the colour. Similarly, the functions c.getGreen() and c.getBlue() return the blue and green components.

Test your component by using it in a simple applet that sets the component to a random colour when the user clicks on a button.

You can find solution in the files RGBChooserComponent.java, TestRGB.java, and TestRGB.html in the folder RGB.


 Printer Friendly Page  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy