2012-07-29 55 views
1

我工作的一個項目與JTabbedPane如何使CardLayout內JTabbedPane的

當我點擊TAB2,它顯示面板2.完成

面板2包括的JButton「下一步」,將切換到PANEL 2.1和JButton「上一頁」,以

切換回面板2,同時仍然在TAB 2

所以,這裏面是一個TAB2卡布局?

感謝您的幫助!

----------------------------- 
TAB 1 | TAB 2 | TAB 3 | 
----------------------------- 
          - 
          - 
      PANEL 2   - 
          - 
          - 
          - 
          - 
     "Previous" "NEXT"  - 
========================== = 

回答

1

您只需要在選項卡中插入JPanel並將其佈局設置爲CardLayout。因此,在每張「卡片」中,您將插入一個新的JPanel。這裏有一個例子:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 

public class Foo extends JFrame { 

    public Foo() { 

     setTitle("Tabs and Cards"); 
     setSize(400, 400); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 

     JTabbedPane tabbedPane = new JTabbedPane(); 

     // needs to be final to be accessed inside the event handlers 
     final JPanel tab1 = new JPanel(); 
     final JPanel tab2 = new JPanel(); 
     tab2.setLayout(new CardLayout()); 

     tabbedPane.addTab("Tab 1", tab1); 
     tabbedPane.addTab("Tab 2", tab2); 


     JPanel tab21 = new JPanel(); 
     tab21.add(new JLabel("2.1")); 

     JPanel tab22 = new JPanel(); 
     tab22.add(new JLabel("2.2")); 

     JPanel tab23 = new JPanel(); 
     tab23.add(new JLabel("2.3")); 

     tab2.add(tab21); 
     tab2.add(tab22); 
     tab2.add(tab23); 


     JButton btnToTab22 = new JButton("Next!"); 
     btnToTab22.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent evt) { 
       // gets the layout, casts it and call next to go to the next card 
       ((CardLayout) tab2.getLayout()).next(tab2); 
      } 
     }); 
     tab21.add(btnToTab22); 

     JButton btnToTab23 = new JButton("Next!"); 
     btnToTab23.addActionListener(new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent evt) { 
       ((CardLayout) tab2.getLayout()).next(tab2); 
      } 
     }); 
     tab22.add(btnToTab23); 

     add(tabbedPane, BorderLayout.CENTER); 

     setVisible(true); 

    } 

    public static void main(String[] args) { 
     new Foo(); 
    } 

} 

我沒有註釋的代碼,因爲沒有那麼複雜,但我認爲你會很容易理解。看看文檔。

+0

謝謝兄弟。你讓我今天一整天都感覺很好。 – 2012-07-29 05:57:18

+0

@ JohnO'really:不客氣。試試這個代碼;) – davidbuzatto 2012-07-29 06:02:25