实现图形界面的切换,可以通过CardLayout,实现面板的切换实现界面的切换。
首先介绍一下CardLayout
CardLayout
对象是容器的布局管理器。它将容器中的每个组件看作一张卡片。一次只能看到一张卡片,容器则充当卡片的堆栈。当容器第一次显示时,第一个添加到CardLayout
对象的组件为可见组件。
主要用到的方法:
方法摘要 |
|
void |
|
void |
|
void |
show(Container parent,String name) |
下面给出测试代码:
import java.awt.CardLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test implements MouseListener{
static JButton bt1;
static JButton bt2;
static JButton bt3;
static JPanel card;
static CardLayout cl;
public Test(){
bt1 = new JButton("按钮1");
bt2 = new JButton("按钮2");
bt3 = new JButton("按钮3");
bt1.addMouseListener(this);
bt2.addMouseListener(this);
bt3.addMouseListener(this);
card = new JPanel();
cl = new CardLayout();
}
public static void main(String[]args){
JFrame jf = new JFrame("界面切换");
Test t = new Test();
card.setLayout(cl);
card.add(bt1);
card.add(bt2);
card.add(bt3);
jf.add(card);
jf.setBounds(400, 100, 200, 100);
jf.setDefaultCloseOperation(3);
jf.setVisible(true);
}
@Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getSource()==bt1){
cl.next(card);
}
else if(arg0.getSource()==bt2){
cl.next(card);
}
else if(arg0.getSource()==bt3){
cl.first(card);
}else{
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
测试结果:实现三个界面的切换