gpt4 book ai didi

java - JPanel 不允许定位组件

转载 作者:行者123 更新时间:2023-12-02 03:44:55 25 4
gpt4 key购买 nike

所以我创建了 2 JFrames

Person

Work Detail

但后来我意识到2 JFrames不是一个好主意。所以我添加了 JTabbedPane然后尝试以 'JPanel 的形式添加不同的选项卡。但我无法像 Jframe 中那样定位组件。它看起来像这样。

Main Menu

但我希望它是这样的

Expected Main Menu

我该怎么做?

最佳答案

如果没有有效的示例,您似乎已经保留了 JPanel 的默认布局(即 FlowLayout)。

首先为每个 View 创建一个自定义面板,这将使管理和将它们应用到 JTabbedPane 变得更加容易。

对于您的即时布局问题,我建议使用 GridBagLayout,因为它的功能强大且灵活......

Layout Layout

import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JTabbedPane tp = new JTabbedPane();
tp.add("Person", new JPanel());
tp.add("Work Detail", new TestPane());

frame.add(tp);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JTextField name;
private JTextField serial;
private JTextField id;
private JTextField email;

private JComboBox level;

public TestPane() {
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.anchor = GridBagConstraints.EAST;
gbc.insets = new Insets(2, 2, 2, 2);

add(new JLabel("Name"), gbc);
gbc.gridx += 2;
add(new JLabel("Sr No"), gbc);
gbc.gridx = 0;
gbc.gridy++;
add(new JLabel("ID"), gbc);
gbc.gridx += 2;
add(new JLabel("Email ID"), gbc);

name = new JTextField(10);
serial = new JTextField(10);
id = new JTextField(10);
email = new JTextField(10);

level = new JComboBox(new String[]{"Manager", "Eng Lead", "Eng Designer", "Jr Designer"});

gbc.anchor = GridBagConstraints.WEST;
gbc.gridx = 1;
gbc.gridy = 0;
add(name, gbc);
gbc.gridx += 2;
add(serial, gbc);
gbc.gridx = 1;
gbc.gridy++;
add(id, gbc);
gbc.gridx += 2;
add(email, gbc);

gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(level, gbc);

gbc.gridy++;
gbc.anchor = GridBagConstraints.CENTER;
add(new JButton("Save"), gbc);
}

}

}

关于java - JPanel 不允许定位组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31285940/

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