Java如何从JTabbedPane删除选项卡?
要从中删除标签,JTabbedPane我们可以使用以下删除方法:
remove(intindex)删除指定索引处的选项卡的方法。
remove(Componentcomponent)删除具有指定子组件的选项卡的方法。
removeAll()删除所有标签的方法。
package org.nhooo.example.swing; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class TabbedPaneRemoveTab extends JPanel { public TabbedPaneRemoveTab() { initializeUI(); } private void initializeUI() { final JTabbedPane pane = new JTabbedPane(JTabbedPane.LEFT); pane.addTab("A Tab", new JPanel()); pane.addTab("B Tab", new JPanel()); JPanel tabPanel = new JPanel(); pane.addTab("C Tab", tabPanel); pane.addTab("D Tab", new JPanel()); pane.addTab("E Tab", new JPanel()); //从JTabbedPane删除最后一个标签 pane.remove(pane.getTabCount() - 1); //删除包含tabPanel组件的选项卡,该组件是 //C标签。 pane.remove(tabPanel); JButton button = new JButton("Remove All Tabs"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //从JTabbedPane删除所有选项卡 pane.removeAll(); } }); this.setLayout(new BorderLayout()); this.setPreferredSize(new Dimension(500, 200)); this.add(pane, BorderLayout.CENTER); this.add(button, BorderLayout.SOUTH); } public static void showFrame() { JPanel panel = new TabbedPaneRemoveTab(); panel.setOpaque(true); JFrame frame = new JFrame("JTabbedPane Demo"); frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); frame.setContentPane(panel); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { TabbedPaneRemoveTab.showFrame(); } }); } }
上面的代码片段的输出是: