gpt4 book ai didi

java - 使用 JTabbedPane 自动扩展

转载 作者:行者123 更新时间:2023-12-02 13:40:50 25 4
gpt4 key购买 nike

我正在尝试让 JTabbedPane 自动扩展到父 JPanel 之上。

当我将所有内容放入主类中时,它就可以工作:

enter image description here

主要:

public class Main extends JFrame {

public Main() {
JTabbedPane tpane = new JTabbedPane();
JPanel panel = new JPanel();
panel.add(new JButton("Button 1"));
tpane.addTab("Tab1", panel);

JPanel panel2 = new JPanel();
panel2.add(new JButton("Button 2"));
tpane.addTab("Tab2", panel2);

this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(tpane);
this.setVisible(true);
}

public static void main(String[] args) {
Main m = new Main();
}
}
<小时/>

但是当我把它放到另一个类中时,它就不再起作用了:

enter image description here

主要:

public class Main extends JFrame {

View view = new View();

public Main() {
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(view, BorderLayout.CENTER); // BorderLayout
this.setVisible(true);
}

public static void main(String[] args) {
Main m = new Main();
}
}

查看:

public class View extends JPanel {

public View() {
JTabbedPane tpane = new JTabbedPane();
JPanel panel = new JPanel();
panel.add(new JButton("Button 1"));
tpane.addTab("Tab1", panel);

JPanel panel2 = new JPanel();
panel2.add(new JButton("Button 2"));
tpane.addTab("Tab2", panel2);

this.add(tpane, BorderLayout.CENTER); // BorderLayout
}
}

最佳答案

框架有边框布局,面板有流布局。

  • 添加到没有约束的边框布局中的组件最终位于中心,并且将拉伸(stretch)到可用的高度和宽度。
  • 添加到流布局的组件将保持其自然大小。
<小时/>

更一般地说,不要设置顶级容器的大小。最好调用 pack(),这将使 TLC 具有容纳其中组件所需的确切大小。要向 GUI 添加空白,请使用布局约束(当布局只有单个组件时不是特别相关)或边框。请参阅this answer一个工作示例。

<小时/>

编辑

I set a BorderLayout to both, Main and View. But the result remained the same.

这是更改 View 布局的结果,如此处所示。

enter image description here

import java.awt.BorderLayout;
import javax.swing.*;

public class Main extends JFrame {

View view = new View();

public Main() {
this.setSize(500, 500);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.add(view);
this.setVisible(true);
}

public static void main(String[] args) {
Main m = new Main();
}
}

class View extends JPanel {

public View() {
super(new BorderLayout()); // Just 1 line difference!
JTabbedPane tpane = new JTabbedPane();
JPanel panel = new JPanel();
panel.add(new JButton("Button 1"));
tpane.addTab("Tab1", panel);

JPanel panel2 = new JPanel();
panel2.add(new JButton("Button 2"));
tpane.addTab("Tab2", panel2);

this.add(tpane);
}
}

关于java - 使用 JTabbedPane 自动扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42747119/

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