JTabbedPane选项卡标题更改字体时保留填充

时间:2018-11-17 04:13:27

标签: java swing jtabbedpane

我正在编写一个自定义BasicTabbedPaneUI,我已覆盖paintText,并更改了其中的fontSize,但这在选项卡的右侧留下了多余的空白。

enter image description here

如您所见,填充物相当大,我希望它与左侧的填充物相同。这是我的代码

import sun.swing.SwingUtilities2;

import javax.swing.*;
import javax.swing.plaf.basic.BasicTabbedPaneUI;
import java.awt.*;

public class UITest {

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        JTabbedPane jTabbedPane = new JTabbedPane();
        jTabbedPane.add(new JPanel(), "This is a test title");
        jTabbedPane.add(new JPanel(), "This is also a test title");
        jTabbedPane.setUI(new LynxTabbedPane());
        jFrame.setContentPane(jTabbedPane);
        jFrame.setSize(300, 100);
        jFrame.setVisible(true);
    }

    public static class LynxTabbedPane extends BasicTabbedPaneUI {

        @Override
        protected void paintText(Graphics g, int tabPlacement, Font font, FontMetrics metrics, int tabIndex, String title, Rectangle textRect, boolean isSelected) {

            Font myFont = new Font(font.getFontName(), Font.BOLD, 10);
            g.setFont(myFont);
            g.setColor(Color.WHITE);

            SwingUtilities2.drawStringUnderlineCharAt(tabPane,
                    g, title,
                    tabPane.getDisplayedMnemonicIndexAt(tabIndex),
                    textRect.x, metrics.getAscent() + 2);
        }
    }
}

我本以为我需要计算tabWidth,所以我尝试覆盖它并从中减去5,但是它没有改变,所以现在我一无所知。

        @Override
        protected int calculateTabWidth(int tabPlacement, int tabIndex, FontMetrics metrics) {
            return super.calculateTabWidth(tabPlacement, tabIndex, metrics) - 5;
        }

1 个答案:

答案 0 :(得分:1)

最终在setFont对象上使用JTabbedPane,因为它会自动处理选项卡的大小

    Font myFont = new Font(tabbedPane.getFont().getFontName(), Font.BOLD, 10);
    tabbedPane.setFont(myFont);