Java Tutorial/Swing/CardLayout — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 17:44, 31 мая 2010

CardLayout methods

MethodDescriptionvoid previous(Container parent)Selects the previous componentvoid first(Container parent)Selects the first componentvoid last(Container parent)Selects the last componentvoid show(Container parent, String name)Selects the component associated with the String object name.


Using a CardLayout Manager

import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TryCardLayout extends JPanel implements ActionListener {
  CardLayout card = new CardLayout(50, 50); // Create layout
  public TryCardLayout() {
    setLayout(card);
    JButton button;
    for (int i = 1; i <= 6; i++) {
      add(button = new JButton(" Press " + i), "Card" + i); // Add a button
      button.addActionListener(this); // Add listener for button
    }
  }
  // Handle button events
  public void actionPerformed(ActionEvent e) {
    card.next(this); // Switch to the next card
  }
  public static void main(String[] args) {
    JFrame aWindow = new JFrame();
    aWindow.setBounds(30, 30, 300, 300);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    aWindow.getContentPane().add(new TryCardLayout());
    aWindow.setVisible(true);
  }
}





What is the CardLayout

  1. Place components like a deck of cards.
  2. Only the "top" component is visible at any one time.



import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class CardLayoutBehaviour extends JFrame {
  protected CardLayout layout;
  public static void main(String[] args) {
    CardLayoutBehaviour ct = new CardLayoutBehaviour();
    ct.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ct.displayTab("Green Tab");
    ct.setSize(400, 300);
    ct.setVisible(true);
  }
  public CardLayoutBehaviour() {
    JPanel tab;
    Container pane = getContentPane();
    layout = new CardLayout();
    pane.setLayout(layout);
    tab = new JPanel();
    tab.setBackground(Color.red);
    pane.add(tab, "Red Tab");
    tab = new JPanel();
    tab.setBackground(Color.green);
    pane.add(tab, "Green Tab");
    tab = new JPanel();
    tab.setBackground(Color.blue);
    pane.add(tab, "Blue Tab");
  }
  public void displayTab(String name) {
    layout.show(this.getContentPane(), name);
  }
}