Home Tutorial Java Swing Java Swing Card Layout

 
 

Share on Google+Share on Google+
Java Swing Card Layout
Posted on: August 19, 2010 at 12:00 AM
Advertisement
This section illustrates you the use of Card layout in java swing.

Java Swing Card Layout

Java technology uses Layout Managers to define the location and size of Graphical User Interface components. It provides different types of Layout Managers which implements the LayoutManager interface. These are:

  • FlowLayout
  • GridLayout
  • BorderLayout
  • GridBagLayout
  • CardLayout
  • SpringLayout

Here we are going to discuss CardLayout. It is a space saving layout manager. Multiple components on card can be added but at a time only one card can be seen.

Here is the code:

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

public class CardLayoutExample extends JFrame {

	private int currentCard = 1;
	private JPanel cardPanel;
	private CardLayout cl;

	public CardLayoutExample() {

		setTitle("Card Layout Example");
		setSize(300, 150);
		cardPanel = new JPanel();

		cl = new CardLayout();
		cardPanel.setLayout(cl);
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel p3 = new JPanel();
		JPanel p4 = new JPanel();
		JLabel lab1 = new JLabel("Card1");
		JLabel lab2 = new JLabel("Card2");
		JLabel lab3 = new JLabel("Card3");
		JLabel lab4 = new JLabel("Card4");
		p1.add(lab1);
		p2.add(lab2);
		p3.add(lab3);
		p4.add(lab4);

		cardPanel.add(p1, "1");
		cardPanel.add(p2, "2");
		cardPanel.add(p3, "3");
		cardPanel.add(p4, "4");
		JPanel buttonPanel = new JPanel();
		JButton b1 = new JButton("Previous");
		JButton b2 = new JButton("Next");
		buttonPanel.add(b1);
		buttonPanel.add(b2);
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (currentCard > 1) {
					currentCard -= 1;
					cl.show(cardPanel, "" + (currentCard));
				}
			}
		});

		b2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (currentCard < 4) {
					currentCard += 1;
					cl.show(cardPanel, "" + (currentCard));
				}
			}
		});
		getContentPane().add(cardPanel, BorderLayout.NORTH);
		getContentPane().add(buttonPanel, BorderLayout.SOUTH);
	}

	public static void main(String[] args) {
		CardLayoutExample cl = new CardLayoutExample();
		cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		cl.setVisible(true);
	}
}

Output:

Advertisement

Related Tags for Java Swing Card Layout:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: August 19, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com