Java中CardLayout布局方式的应用

时间:2021-06-22 22:14:12
 import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Container; import javax.swing.JButton;
import javax.swing.JFrame; public class CardLayoutDemo {
public static void main(String[] args) {
//新建一个JFrame框架
JFrame frame = new JFrame("CardLayout");
frame.setSize(600, 400);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); final Container cp = frame.getContentPane();//得到一个内容面板;final标记的为常量,只能赋值一次
final CardLayout cardlayout = new CardLayout();//因为后期会对layout进行操作,才将其单独定义出来
cp.setLayout(cardlayout);//cp.setLayout(new CardLayout())的方式不可行,会出现异常
Color[] colors = { Color.white, Color.GRAY, Color.PINK, Color.cyan }; for (int i = 0; i < colors.length; i++) {
String name = "card" + String.valueOf(i + 1);
JButton button = new JButton(name);
button.setBackground(colors[i]);
cp.add(name, button);
} frame.setVisible(true);
/**
* 要点是创建线程时,要重写Thread类中的run方法
*/
Thread thread = new Thread() {
public void run() {
while (true) {
try {
Thread.sleep(400);
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* cardLayout的next是另外一个内容面板
*/
cardlayout.next(cp);
}
}
};
thread.start();//启动线程
}
}