您只需要在選項卡中插入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();
}
}
我沒有註釋的代碼,因爲沒有那麼複雜,但我認爲你會很容易理解。看看文檔。
謝謝兄弟。你讓我今天一整天都感覺很好。 – 2012-07-29 05:57:18
@ JohnO'really:不客氣。試試這個代碼;) – davidbuzatto 2012-07-29 06:02:25