5

我有一个 jTabbedPane,里面有多个选项卡。我正在尝试将选定/活动选项卡的标题文本加粗。有没有一种简单的方法可以做到这一点?

4

3 回答 3

0
JTabbedPane pane = new JTabbedPane();
pane.addChangeListener(new ChangeListener(){

 @Override
 public void stateChanged(ChangeEvent e) {
     JTabbedPane source = (JTabbedPane) e.getSource();
     // Set all tabs to PLAIN font
     for(int i = 0; i < source.getTabCount(); i++) {
         Component c = source.getTabComponentAt(i);
         c.setFont(c.getFont().deriveFont(Font.PLAIN));
     }
     Component selectedComp = source.getTabComponentAt(source.getSelectedIndex());
     // Set selected component to BOLD
     selectedComp.setFont(selectedComp.getFont().deriveFont(Font.BOLD));
     }
});

试试这个,我写的很快,也许你需要对初始标签做一些调整,不确定。

也不太确定您是否需要 JTabbedPane.getTabComponentAt(int idx) 或 JTabbedPane.getComponentAt(int idx) 虽然我认为第一个版本是正确的。

于 2013-08-21T17:04:33.660 回答
0

我知道这个问题很久以前就被问过了,但我最近也想这样做。我在这里找到了答案。解决方案是以下两件事之一:

  1. 利用tabbedPane.setTitleAt(currSelextedIdx, "<html><b>My tab title</b></html>");
  2. 为选项卡式窗格创建自己的 UI 实现

我个人使用第一个选项并将所有其他选项卡设置回更改时的常规选项卡标题。在初始化所有选项卡后,我还将初始选项卡设为粗体(这可以在初始化时完成)。

于 2020-03-08T14:17:25.380 回答
0

到目前为止我找到的最简单的解决方案。在 JTabbedPane 的子类中,重写如下两个方法。添加选项卡后,原始标题将作为选项卡组件的客户端属性保留。When the selected tab changes, the current tab title is restored to the raw title and the next tab title is set to bold with HTML.

public class MyTabbedPane extends JTabbedPane {

    ...
    
    @Override
    public void insertTab(String title, Icon icon, Component component, String tip, int index) {
        ((JComponent)component).putClientProperty("title", title);
        super.insertTab(title, icon, component, tip, index);
    }
    
    @Override
    public void setSelectedIndex(int index) {
        int currentIndex = getSelectedIndex();
        if (currentIndex >= 0) {
            JComponent previous = (JComponent) getComponentAt(currentIndex);
            String title = (String) previous.getClientProperty("title");
            setTitleAt(currentIndex, title);
        }
        super.setSelectedIndex(index);

        JComponent current = getSelectedComponent();
        String title = (String) current.getClientProperty("title");
        setTitleAt(index, "<html><b>" + title + "</b></html>");
    }

}
    
于 2022-01-07T12:26:31.360 回答