我被委托使用Swing在Java中设计基本用户界面(UI),但我遇到了布局问题。我想创建类似这个的东西,但是我尝试使用GridBagLayout却导致结果非常混乱。有人能提供一些建议来帮助我像这样布置GUI吗?
我有一个JTabbedPane,在其中添加两个选项卡,每个选项卡都包含一个包含我的控件的JPanel。
我有一个JTabbedPane,在其中添加两个选项卡,每个选项卡都包含一个包含我的控件的JPanel。
![我想要的布局](https://istack.dev59.com/Lj4Z1.webp)
我建议:
JPanel pTextBox
来容纳所有标签和文本框JPanel pButtons
来容纳所有按钮JPanel pAll
来容纳pTextBox
、pButtons
和表格这里是一些代码...我无法正确显示JTextFields,所以你需要修复它。
主要:
import javax.swing.SwingUtilities;
public class Main {
public static void main(String [] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Panel panel = new Panel();
}
});
}
}
面板:
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JTextField;
public class Panel extends JPanel{
private JFrame frame;
private JLabel label1;
private JLabel label2;
private JLabel label3;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;
private JButton button1;
private JButton button2;
private JButton button3;
private JTable table;
public Panel() {
label1 = new JLabel("label1");
label2 = new JLabel("label2");
label3 = new JLabel("label3");
textField1 = new JTextField("textField1", 20);
textField2 = new JTextField("textField2", 20);
textField3 = new JTextField("textField3", 100);
button1 = new JButton("Hello");
button2 = new JButton("Goodbye");
button3 = new JButton("Love");
table = new JTable(20,20);
frame = new JFrame("My application");
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frame.setVisible(true);
this.setOpaque(true);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.weightx = 1;
gc.weighty =1;
gc.fill = GridBagConstraints.NONE;
gc.gridx = 0;
gc.gridy = 0;
// gc.anchor = GridBagConstraints.WEST;
add(label1, gc);
gc.gridx = 2;
gc.gridy = 0;
//gc.anchor = GridBagConstraints.EAST;
add(textField1, gc);
gc.gridx = 0;
gc.gridy = 1;
//gc.anchor = GridBagConstraints.WEST;
add(label2, gc);
gc.gridx = 2;
gc.gridy = 1;
//gc.anchor = GridBagConstraints.EAST;
add(textField2, gc);
gc.gridx = 0;
gc.gridy = 2;
//gc.anchor = GridBagConstraints.WEST;
add(label3, gc);
gc.gridx = 2;
gc.gridy = 2;
//gc.anchor = GridBagConstraints.EAST;
add(textField3, gc);
gc.gridx = 0;
gc.gridy = 3;
//gc.anchor = GridBagConstraints.WEST;
add(button1, gc);
gc.gridx = 1;
gc.gridy = 3;
gc.anchor = GridBagConstraints.CENTER;
add(button2, gc);
gc.gridx = 2;
gc.gridy = 3;
// gc.anchor = GridBagConstraints.EAST;
add(button3, gc);
gc.gridx = 1;
gc.gridy = 4;
gc.anchor = GridBagConstraints.CENTER;
add(table, gc);
frame.add(this);
}
}