我有一个 JTabbedPane,我希望选项卡仅位于一行,但没有滚动箭头。我希望选项卡填充父 JFrame 的宽度。
我有以下代码:
public class TabbedPaneExample extends JFrame {
public TabbedPaneExample() {
super("My TabbedPane");
setup();
}
private void setup() {
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.add("The first tab", new JPanel());
tabbedPane.add("The second tab", new JPanel());
tabbedPane.add("The third tab", new JPanel());
tabbedPane.add("The fourth tab", new JPanel());
tabbedPane.add("The fith tab", new JPanel());
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
Container pane = this.getContentPane();
pane.setLayout(new BorderLayout());
this.add(tabbedPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
TabbedPaneExample example = new TabbedPaneExample();
example.pack();
example.setVisible(true);
}
}
我只找到了
setTabLayoutPolicy
方法,但理想情况下我想获得选项卡式窗格的首选大小并在我的框架中使用它。
理想情况下,我想获得选项卡式窗格的首选大小
是的,这就是关键。默认首选大小基于添加到选项卡式窗格中的最大组件的大小,而不是选项卡本身。
所以你需要自定义
getPreferredSize()
方法来考虑选项卡:
import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.*;
public class TabbedPaneExample2
{
private static void createAndShowGUI()
{
JTabbedPane tabbedPane = new JTabbedPane()
{
//@Override
public Dimension getPreferredSize()
{
Dimension size = super.getPreferredSize();
TabbedPaneUI ui = getUI();
Rectangle lastTab = ui.getTabBounds(this, this.getTabCount() - 1);
int tabsWidth = lastTab.x + lastTab.width;
Insets border = UIManager.getInsets("TabbedPane.contentBorderInsets");
tabsWidth += border.left + border.right;
if (tabsWidth > size.width)
size.width = tabsWidth;
return size;
}
};
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
JPanel first = new JPanel();
first.setPreferredSize( new Dimension(400, 400) );
tabbedPane.add("The first tab", first);
tabbedPane.add("The second tab", new JPanel());
tabbedPane.add("The third tab has longer text", new JPanel());
tabbedPane.add("The fourth tab", new JPanel());
tabbedPane.add("The fith tab", new JPanel());
JFrame frame = new JFrame("TabbedPaneExample2");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(tabbedPane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}