转自:http://wangdehe88.blog.163.com/blog/static/1233286620096883358602/
1.CardLayout
CardLayout
对象是容器的布局管理器。它将容器中的每个组件当作一个卡片来处理。在某一时间,只有一个卡片是可见的,容器象一个卡片堆栈一样工作。
CardLayout
定义了一系列方法,来允许一个应用顺序地翻动这些卡片,或显示一个指定的卡片。
以下为示例:
CardLayout cardlayout = new CardLayout();
JPanel panel=new JPanel(cardlayout);
JPanel panel1=new JPanel();
JPanel panel2=new JPanel();
panel.add(panel1,"name1");
panel.add(panel2,"name2");
//用下面代码切换
cardlayout.show(panel,"name1");
//cardlayout.show(pane2,"name2");
2.JTabbedPane
JTabbedPane在Swing中实现选项窗格,它可以把多个组件放在多个选项卡中,从而使页面不致拥挤,其选项卡的形式也能为程序增色不少。
选项窗格和分隔窗格类似,创建出来需要添加到设置好布局的面板中,通常我们可以设置布局为1*1的网格布局或是边界布局。
选项窗格内部可以放置多个选项页,每个选项页都可以容纳一个JPanel作为子组件,我们只要设计好需要添加到选项页的面板即可。
JTabbedPane效果
创建JTabbedPane
// 创建选项窗格
JTabbedPane tabPane = new JTabbedPane();
// 设置面板布局为网格布局
this.setLayout(new GridLayout(1,1));
tabPane.setTabPlacement(JTabbedPane.TOP);// 设定选项卡放在上部
this.add(tabPane);// 将选项窗格放置在面板中
// 创建一个StockPanel面板并添加到选项窗格,这是指定图标的方法
StockPanel stockPanel=new StockPanel();
tabPane.addTab("库存页面", new ImageIcon(TabbedPanel.class
.getResource("/stock.gif")), stockPanel);
ImportPanel importPanel=new ImportPanel();
tabPane.addTab("进货页面", new ImageIcon(TabbedPanel.class
.getResource("/import.gif")), importPanel);
// 创建一个SaledPanel面板并添加到选项窗格,这是不指定图标的方法
SaledPanel saledPanel=new SaledPanel();
tabPane.addTab("已售页面", saledPanel);
tabPane.setSelectedIndex(0);
3.使用jpanel的去除和增加
那些JPanel都作为你的JFrame的属性。 然后点击时触发事件,删除不需要的选项卡,添加需要的JPanel this.getContentPane().remove(jPanel1); this.getContentPane().add(jPanel2); this.validate(); 示例代码如下import javax.swing.*; import java.awt.*; import java.awt.event.*; class Test extends JFrame { JPanel contPanel = new JPanel(); JPanel pane1 = new JPanel(); JPanel pane2 = new JPanel(); JButton next = new JButton("下一个"); JButton pre = new JButton("上一个"); public Test() { setBounds(0,0,200,300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); contPanel.add(pane1); pane1.add(next); pane2.add(pre); next.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { contPanel.remove(pane1); contPanel.add(pane2); contPanel.revalidate(); contPanel.repaint(); } }); pre.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e) { contPanel.remove(pane2); contPanel.add(pane1); contPanel.revalidate(); contPanel.repaint(); } }); setContentPane(contPanel); setVisible(true); } public static void main(String [] args) { new Test(); } } 因为你的JPanel和JFrame是独立的类,所以可以在其中增加几个get..和set...的函数,把相应的对象赋过去