【问题标题】:How to change the width of tab labels in java but keep the "selection" options如何在java中更改选项卡标签的宽度但保留“选择”选项
【发布时间】:2014-06-01 00:09:20
【问题描述】:

我的程序中有一个JTabbedPane 对象,我重写了getForegroundAtgetBackgroundAt 方法,以便在选择或不选择选项卡时具有不同的背景颜色。我想改变标签的宽度和高度。我设法使用类似于以下的代码来做到这一点:

 jtp.addTab("<html><body><table width='200'>Main</table></body></html>", mainPanel);

问题在于,如果我使用此 html 代码更改选项卡的宽度,则不再调用我覆盖的方法,因为这些选项是使用 html 代码设置的。有没有办法解决这个问题?是否有我可以使用的 html 代码来更改选项卡的背景颜色,具体取决于它是否被选中?谢谢。

【问题讨论】:

    标签: java html swing jtabbedpane


    【解决方案1】:

    这是通过覆盖 JTabbedPane 的 UI 中的 calculateTabWidth(...) 来更改选项卡宽度的一种方法:

    编辑: MadProgrammer 的评论是正确的。我已将示例从 BasicTabbedPaneUI 更改为 MetalTabbedPaneUI,因为这是该示例使用的默认 UI。如果您要为您的应用指定特定的 L&F,请相应地更改 UI。

    import java.awt.*;
    import javax.swing.*;
    import javax.swing.plaf.metal.*;
    
    public class CustomTabWidthDemo implements Runnable
    {
      public static void main(String[] args)
      {
        SwingUtilities.invokeLater(new CustomTabWidthDemo());
      }
    
      public void run()
      {
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.setUI(new MetalTabbedPaneUI()
        {
          @Override
          protected int calculateTabWidth(int tabPlacement, int tabIndex,
                                          FontMetrics metrics)
          {
            int width = super.calculateTabWidth(tabPlacement, tabIndex, metrics);
            int extra = tabIndex * 50;
            return width + extra;
          }
        });
    
        tabbedPane.addTab("JTable", new JScrollPane(new JTable(5,5)));
        tabbedPane.addTab("JTree", new JScrollPane(new JTree()));
        tabbedPane.addTab("JSplitPane", new JSplitPane());
    
        JPanel p = new JPanel();
        p.add(tabbedPane);
    
        JFrame frame = new JFrame();
        frame.setContentPane(p);
        frame.pack();
        frame.setVisible(true);
      }
    }
    

    【讨论】:

    • 只要您知道这将完全破坏当前安装的外观和感觉的外观
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    • 2013-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多