CardLayout 是实现了card 的效果; 你如果要有效果, JPanel 中加事件, 用CardLayout 中的 next(Container parent) 方法
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardTest extends JFrame
{
JPanel c1;
CardLayout cardpanel;
public CardTest()
{
c1=new JPanel();
cardpanel =new CardLayout();
c1.setLayout(cardpanel);
JButton b1=new JButton("a");
JButton b2=new JButton("b");
ActionListener action=new ActionListener(){
public void actionPerformed(ActionEvent e)
{
cardpanel.next(c1);
}
};
b1.addActionListener(action);
b2.addActionListener(action);
c1.add(b1,"1");
c1.add(b2,"2");
getContentPane().add(c1);
setSize(100,200);
setVisible(true);
}
public static void main (String args[])
{
new CardTest();
}
}点击button 就可以display the next button
for example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardTest extends JFrame
{
JPanel c1;
CardLayout cardpanel;
public CardTest()
{
c1=new JPanel();
cardpanel =new CardLayout();
c1.setLayout(cardpanel);
JButton b1=new JButton("a");
JButton b2=new JButton("b");
ActionListener action=new ActionListener(){
public void actionPerformed(ActionEvent e)
{
cardpanel.next(c1);
}
};
b1.addActionListener(action);
b2.addActionListener(action);
c1.add(b1,"1");
c1.add(b2,"2");
getContentPane().add(c1);
setSize(100,200);
setVisible(true);
}
public static void main (String args[])
{
new CardTest();
}
}点击button 就可以display the next button
JPanel c2 = new JPanel();
CardLayout cardLayout2 = new CardLayout();
c2.setLayout( cardLayout2 );
c1.add(c2);
这时我遇到了问题,c2没有显示出一个CardLayout所应有的性质.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class CardTest extends JFrame
{
JPanel c1;
JPanel c2;
JPanel c3;
CardLayout cardpanel;
CardLayout cardpanel1;
CardLayout card;
Container con;
static int i=0;
public CardTest()
{
c1=new JPanel();
c2=new JPanel();
c3=new JPanel();
card=new CardLayout();
cardpanel =new CardLayout();
cardpanel1 =new CardLayout();
c1.setLayout(cardpanel);
c2.setLayout(cardpanel1);
c3.setLayout(card);
JButton b1=new JButton("a");
JButton b2=new JButton("b");
JButton b3=new JButton("c");
JButton b4=new JButton("d");
ActionListener action=new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if (i<c1.getComponentCount())
{
cardpanel.next(c1);
i++;
}
if (i==c1.getComponentCount())
{
card.next(c3) ;
i++;
}
if (i<=c2.getComponentCount()+3)
{
cardpanel1.next(c2);
i++ ;
}
if(i>=c2.getComponentCount()+c1.getComponentCount()+1)
{
System.out.println(i);
i=0;
card.next(c3);
}
}
};
b1.addActionListener(action);
b2.addActionListener(action);
b3.addActionListener(action);
b4.addActionListener(action);
c1.add(b1,"1");
c1.add(b2,"2");
c2.add(b3,"3");
c2.add(b4,"4");
c3.add(c1,"c1");
c3.add(c2,"c2");
con=getContentPane();
con.add(c3);
setSize(100,200);
setVisible(true);
}
public static void main (String args[])
{
new CardTest();
}
}