JAVA GUI学习 - JTabbedPane选项卡组件学习
1 public class JTabbedPaneKnow extends JFrame 2 { 3 JTabbedPane jTabbedPane; 4 JPanel jPanelRed; 5 JPanel jPanelGreen; 6 JPanel jPanelYellow; 7 JPanel jPanelBlue; 8 public JTabbedPaneKnow() 9 { 10 init(); 11 this.setBounds(200, 50, 500, 500); 12 this.setTitle("选项卡 - 知识"); 13 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 14 15 this.add(jTabbedPane); 16 } 17 public void init() 18 { 19 jPanelBlue = new JPanel();jPanelBlue.setBackground(Color.blue);jPanelBlue.setName("蓝色卡牌"); 20 jPanelGreen = new JPanel();jPanelGreen.setBackground(Color.green);jPanelGreen.setName("绿色卡牌"); 21 jPanelRed = new JPanel();jPanelRed.setBackground(Color.red);jPanelRed.setName("红色卡牌"); 22 jPanelYellow = new JPanel();jPanelYellow.setBackground(Color.yellow);jPanelYellow.setName("黄色卡牌"); 23 24 //第一个参数:选项卡的标题所在位置:上下左右 25 //第二个参数:即选项卡呈现的方式:当窗口变小时:卡标题向下排列,或不重排列出现滚动条 26 jTabbedPane = new JTabbedPane(JTabbedPane.TOP,JTabbedPane.SCROLL_TAB_LAYOUT); 27 28 //第一个参数:即选项卡显示的标题 29 //第二个参数:即选项卡没张卡对应的面板 30 jTabbedPane.add("蓝色卡牌", jPanelBlue);jTabbedPane.add("绿色卡牌", jPanelGreen); 31 jTabbedPane.add("红色卡牌", jPanelRed);jTabbedPane.add("黄色卡牌", jPanelYellow); 32 33 //设置默认的选项卡页,方式一:通过选项卡的索引 34 jTabbedPane.setSelectedIndex(1); 35 36 //设置默认的选项卡页,方式二:通过选项卡变量名 37 jTabbedPane.setSelectedComponent(jPanelGreen); 38 39 //获取当前卡页的选项卡索引 40 int index = jTabbedPane.getSelectedIndex(); 41 //获取当前卡页的选项卡面板 42 JPanel jPanel = (JPanel) jTabbedPane.getSelectedComponent(); 43 System.out.println(jPanel.getName()); 44 45 //为选项卡添加监听器 46 jTabbedPane.addChangeListener(new JTabbedPaneChangeListener()); 47 } 48 private class JTabbedPaneChangeListener implements ChangeListener 49 { 50 @Override 51 public void stateChanged(ChangeEvent e) 52 { 53 JTabbedPane jTabbedPane = (JTabbedPane) e.getSource(); 54 JOptionPane.showMessageDialog(null, ((JPanel)jTabbedPane.getSelectedComponent()).getName()+":被打开了"); 55 } 56 } 57 public static void main(String[] args) 58 { 59 JTabbedPaneKnow jTabbedPaneKnow = new JTabbedPaneKnow(); 60 jTabbedPaneKnow.setVisible(true); 61 } 62 63 }