我遇到问题,我的 JPanel
未设置大小。我不确定是否与我的 JTab
或 JFrame
有关。我正在使用 GridBagLayout 布局管理。并且由于某种原因无法设置大小。
这是一个虚拟代码,遵循与我的原始源代码相同的逻辑:
FirstPanel.java
import javax.swing.*;
import java.awt.*;
public class FirstPanel extends JPanel {
private JLabel label1 = new JLabel("Label 1");
private JTextField textField1 = new JTextField();
private GridBagConstraints c = new GridBagConstraints();
public FirstPanel() {
//Size is not overriding
Dimension size = getPreferredSize();
size.width = 100;
setPreferredSize(size);
setBorder(BorderFactory.createTitleBorder("Border Title");
setLayout(new GridBagLayout());
addComponents();
}
private void addComponents() {
c.gridx = 0;
c.gridy = 0;
c.anchor = GridBagConstraints.NORTHWEST;
c.insets = new Insets(5, 0, 0, 0);
add(label1, c);
c.gridx = 1;
add(textField1, c);
c.weightx = 1;
c.weighty = 1;
add(new JLabel(""), c);
}
}
MainPanel.java
import javax.swing.*;
import java.awt.*;
public class MainPanel {
private JFrame frame = new JFrame("App");
private JPanel panel1 = new JPanel(new GridBagLayout());
private GridBagConstraints c = new GridBagConstraints();
private JTabbedPane tabPane = new JTabbedPane();
public MainPanel() {
addComponents();
frame.add(tabPane);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 350);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
}
private void addComponents() {
tabPane.addTab("Tab 1", new FirstPanel());
}
}
Main.java
public class Main {
public static void main(String[] args) {
new MainPanel();
}
}
最佳答案
Or at least have two JPanels,
正是如此。
首先,使用添加到选项卡式 Pane 的 BorderLayout
创建主面板。
然后你就有了第二个面板用于标签和文本字段(使用你想要的任何布局管理器)。然后将此面板添加到 BorderLayout.LINE_START
中。
然后将包含 JTable 的滚动 Pane 添加到主面板的 BorderLayout.CENTER
中。
阅读 Layout Manager 上的教程。根据需要使用不同的布局管理器嵌套面板。
want to have JTable taking 50% of the other side.
选择像 50% 这样的随机数并不是设计 GUI 的方法。如果框架变小/变大会发生什么。空间会发生什么?设计布局时要考虑到灵 active ,就像设计浏览器窗口一样。总是有固定区域,其大小由添加的组件决定,并且有一个灵活区域,可以根据需要增大/缩小。
关于java - 设置 Size 不会在 Java 上覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46498687/