一个CardLayout的例子:
package gui.test10;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.CardLayout;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
/**
* 取消布局管理器:
* container.setLayout(null);
* 采用绝对定位:setBounds(....)
*
* @author junlas
*
*/
public class TestCardLayout extends Frame {
private CardLayout cl = new CardLayout();
//
Panel plCenter = new Panel();
public TestCardLayout() {
Panel plWest = new Panel();
plWest.setLayout(new GridLayout(3, 1));
Button btnPrev = new Button("prev");
Button btnNext = new Button("next");
Button btnThree = new Button("three");
plWest.add(btnPrev);
plWest.add(btnNext);
plWest.add(btnThree);
plCenter.setLayout(cl);
plCenter.add(new Button("one"),"1");
plCenter.add(new Button("two"),"2");
plCenter.add(new Button("three"),"3");
plCenter.add(new Button("four"),"4");
plCenter.add(new Button("five"),"5");
myActionListener ma = new myActionListener();
btnPrev.addActionListener(ma);
btnNext.addActionListener(ma);
btnThree.addActionListener(ma);
//
add(plWest,BorderLayout.WEST);
add(plCenter);
//
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
private class myActionListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("prev")){
cl.previous(plCenter);
}else if(e.getActionCommand().equals("next")){
cl.next(plCenter);
}else{
cl.show(plCenter, "3");
}
}
}
public static void main(String[] args) {
TestCardLayout mainFrame = new TestCardLayout();
mainFrame.setSize(400, 400);
mainFrame.setTitle("TestCardLayout");
mainFrame.setVisible(true);
}
}