CardFrame.java Source code

Java tutorial

Introduction

Here is the source code for CardFrame.java

Source

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

class CardFrame extends JFrame implements ActionListener {
    JButton nextCard = new JButton("Next Card >");
    JButton prevCard = new JButton("< Previous Card");
    JButton firstCard = new JButton("<< First Card");
    JButton lastCard = new JButton("Last Card >>");
    JPanel cardPanel = new JPanel();

    CardLayout cardLayout = new CardLayout(10, 10);

    public CardFrame(String title) {
        setLayout(new BorderLayout(10, 10));
        nextCard.addActionListener(this);
        prevCard.addActionListener(this);
        firstCard.addActionListener(this);
        lastCard.addActionListener(this);

        Panel buttonsPanel = new Panel(new FlowLayout(FlowLayout.CENTER));
        buttonsPanel.add(firstCard);
        buttonsPanel.add(prevCard);
        buttonsPanel.add(nextCard);
        buttonsPanel.add(lastCard);

        setCardLayout();
        add(BorderLayout.CENTER, cardPanel);
        add(BorderLayout.NORTH, buttonsPanel);
    }

    private void setCardLayout() {
        cardPanel.setLayout(cardLayout);

        Label one = new Label("CARD 1", Label.CENTER);
        Label two = new Label("CARD 2", Label.CENTER);
        Label three = new Label("CARD 3", Label.CENTER);
        Label four = new Label("CARD 4", Label.CENTER);
        Label five = new Label("CARD 5", Label.CENTER);
        cardPanel.add(one, "one");
        cardPanel.add(two, "two");
        cardPanel.add(three, "three");
        cardPanel.add(four, "four");
        cardPanel.add(five, "five");

        cardLayout.show(cardPanel, "one");
    }

    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource().equals(nextCard)) {
            cardLayout.next(cardPanel);
        } else if (ae.getSource().equals(prevCard)) {
            cardLayout.previous(cardPanel);
        } else if (ae.getSource().equals(lastCard)) {
            cardLayout.last(cardPanel);
        } else if (ae.getSource().equals(firstCard)) {
            cardLayout.first(cardPanel);
        }
    }
}