Java使用卡片布局管理器

package com.han;

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

/**
 * 使用卡片布局管理器
 * @author HAN
 *
 */
public class CardLayout_1 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5255525755443566487L;

	public CardLayout_1() {
		// TODO Auto-generated constructor stub
		Container container = getContentPane();
		final CardLayout cardLayout = new CardLayout();
		final JPanel cardPanel = new JPanel(cardLayout);
		String[] cardNames = { "卡片A", "卡片B", "卡片C" };
		for (int i = 0; i < cardNames.length; i++) {
//			JLabel label = new JLabel(cardNames[i]);
			JLabel label = new JLabel(cardNames[i], SwingConstants.CENTER);
//			cardPanel.add(label);
			cardPanel.add(label, cardNames[i]);
		}
		container.add(cardPanel, BorderLayout.CENTER);
		JPanel buttonPanel = new JPanel(); // by default, the flow layout
		container.add(buttonPanel, BorderLayout.SOUTH);
		String[] buttonNames = { "第一个", "前一个", "卡片A", "卡片B", "卡片C",
				"后一个", "最后一个" };
		for (int i = 0; i < buttonNames.length; i++) {
			final JButton button = new JButton(buttonNames[i]);
			buttonPanel.add(button);
			button.addActionListener(new ActionListener() {

				@Override
				public void actionPerformed(ActionEvent e) {
					// TODO Auto-generated method stub
					String buttonText = button.getText();
					if (buttonText.equals("第一个")) {
						cardLayout.first(cardPanel);
					} else if (buttonText.equals("前一个")) {
						cardLayout.previous(cardPanel);
					} else if (buttonText.equals("卡片A")) {
						cardLayout.show(cardPanel, "卡片A");
					} else if (buttonText.equals("卡片B")) {
						cardLayout.show(cardPanel, "卡片B");
					} else if (buttonText.equals("卡片C")) {
						cardLayout.show(cardPanel, "卡片C");
					} else if (buttonText.equals("后一个")) {
						cardLayout.next(cardPanel);
					}else {
						cardLayout.last(cardPanel);
					}
				}

			});
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		CardLayout_1 frame = new CardLayout_1();
		frame.setTitle("使用卡片布局管理器");
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.pack();
	}

}


你可能感兴趣的:(java,c,String,Class,button,Constructor)