In our application that has a JTabbedPane with unlimited tabs, when the width of the tabs exceeds the tabbed pane's width, the tabs start wrapping into several rows.然后当您单击上面一行中的一个选项卡时,完整的行会下降并出现在前景中。对于在多个选项卡之间点击的用户来说,这是非常困惑的,因为不可能跟踪选项卡顺序。
我怎么能 - 将选项卡钉在固定位置,同时将它们的内容放在前面(尽管这会在视觉上破坏选项卡的隐喻,但我不在乎),或者 - 将行数限制为一(这样选项卡变得非常窄而不是换行)?
最佳答案
经过几个小时的研究,我终于找到了一个干净的解决方案。
首先,确定您使用的是哪个 UI 类。在使用 UIManager.setLookAndFeel()
初始化 L&F 后放置以下代码:
for (Map.Entry<Object, Object> entry : UIManager.getDefaults().entrySet()) {
boolean isStringKey = entry.getKey().getClass() == String.class ;
String key = isStringKey ? ((String) entry.getKey()):"";
if (key.equals("TabbedPaneUI")) {
System.out.println(entry.getValue());
}
}
在我的例子中,它打印 com.sun.java.swing.plaf.windows.WindowsTabbedPaneUI
。如果您使用不同的 L&F,这可能是另一个类(或者即使您使用的是另一个操作系统,如果您使用操作系统默认值)。
接下来,只需实例化该类(它扩展了 BasicTabbedPaneUI),并覆盖有问题的方法:
WindowsTabbedPaneUI jtpui = new WindowsTabbedPaneUI() {
@Override protected boolean shouldRotateTabRuns(int i) {
return false;
}
};
如果 eclipse 不识别类,并且在您键入类的全名时给出“访问限制”错误,请参阅以下问题:Access restriction: The type 'Application' is not API (restriction on required library rt.jar)
最后,只需为您的 JTabbedPane 设置该 UI:
JTabbedPane jtp = new JTabbedPane();
jtp.setUI(jtpui);
但是,有一个问题:一些L&F没有考虑到标签行的非滚动,结果很丑。
要解决这个问题(我只在 Windows L&F 上测试过),请在初始化 L&F 后立即添加以下内容:
UIManager.getDefaults().put("TabbedPane.tabRunOverlay", 0);
关于java - JTabbedPane 中固定位置或一行中的选项卡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9636601/