如何在选项卡中添加关闭按钮,JTabbedPane

问题描述:

我正在使用JTabbedPane,并且我想向选项卡添加一个关闭按钮。如何在选项卡中添加关闭按钮,JTabbedPane

我创建了一个JButton,带有一个:ActionListener,当你点击的时候,这个选项卡将被逐个打开。

而且,我创建了一个JTabbedPane中......

//Tabbed. 
JTabbedPane Tabbedr = new JTabbedPane(); 
File F = new File("HTML1.html"); 
Frame.getContentPane().add(Tabbedr); 
Tabbedr.addTab(F.getName()); 

//Button. 
JButton Close = new JButton(); 
Close.addActionListener(new ActionListener(){ 
public void actionPerformed(ActionEvent a){ 
Tabbedr.remove(1);}}); 

所以,在这里所有的罚款,但我不知道如何添加将JButton“关闭”,我的标签。正如在一些着名的编辑,

要测试按钮,我把它添加到一个工具栏,但我想把这里面的标签。例如:你好,txt“X”。

¿有人可以帮助我吗?感谢您阅读和您的时间。

+0

如果这不是['ButtonTabComponent'](https://docs.oracle.com/javase/tutorial/uiswing/components/tabbedpane.html)的重复,请编辑您的问题以包含[mcve]显示你目前的做法。 – trashgod

public class CustomTabbedPane extends JTabbedPane { 

    public CustomTabbedPane() { 

     // Add panel to tab screen 
     JPanel tab1Panel = new JPanel(); 
     addTab(null, null, tab1Panel, ""); 

     // Add label and button to the tab name 
     JPanel tab1 = new JPanel(); 
     temp.add(new JLabel("Tab Name")); 
     temp.add(new JButton("x")); 
     setTabComponentAt(0, tab1); 
    } 
} 

当然,你想要添加一个ActionListener到JButton并配置它,以便在按下按钮时该选项卡消失。

为了使它看起来不错,我建议你摆脱对JButton的边距,

button.setMargin(new Insets(0, 0, 0, 0)) 

删除边框,

button.setBorder(BorderFactory.createEmptyBorder()); 

,并设置TAB1的JPanel到“空”布局来手动放置“x”按钮和标签。