gpt4 book ai didi

java - JPanel 中的 JTabbedPane?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:57:49 34 4
gpt4 key购买 nike

当我想在我的 jpanel 中添加选项卡时,我遇到了一个简单的问题。选项卡的对齐方式变为水平对齐而不是垂直对齐,这看起来像废话 =/。

看起来像这样:

enter image description here

如果我放弃面板并将 tabbedPane 直接添加到框架,一切正常。如果您取消注释这三行代码并删除 getContentPane().add(jtp);,您可以重现我的问题。

工作代码:

public class TabbedPane extends JFrame
{
public TabbedPane()
{
setTitle("Tabbed Pane");
setSize(300, 300); // set size so the user can "see" it
JTabbedPane jtp = new JTabbedPane();

// JPanel panel = new JPanel();//uncomment all three lines
// panel.add(jtp);
// getContentPane().add(panel);

getContentPane().add(jtp);//remove me

JPanel jp1 = new JPanel();// This will create the first tab
JPanel jp2 = new JPanel();// This will create the second tab

JLabel label1 = new JLabel();
label1.setText("This is Tab 1");
jp1.add(label1);

jtp.addTab("Tab1", jp1);
jtp.addTab("Tab2", jp2);

JButton test = new JButton("Press");
jp2.add(test);

setVisible(true); // otherwise you won't "see" it
}

public static void main(String[] args)
{
TabbedPane tab = new TabbedPane();
}

}

非常感谢!

最佳答案

If I discard the panel instead and add the tabbedPane directly to the frame, everything works fine.

JPanel 的默认布局是 FlowLayout,它“让每个组件采用其自然(首选)大小”。 JFrame 的默认布局是 BorderLayout,其 CENTER 忽略首选大小。在任何一种情况下,调用 setSize() 都会阻止布局最初运行;重新调整框架大小以查看效果。相反,使用 pack(),它“使此 Window 的大小适合其子组件的首选大小和布局。”

setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true); // otherwise you won't "see" it

关于java - JPanel 中的 JTabbedPane?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14553024/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com