我正在尝试创建一个使用 Java 与 mySQL 数据库交互的客户端-服务器应用程序。截至目前,我并不担心应用程序的任何功能。我目前只关心布局。几个小时以来,我一直在尝试构建 GUI 的外观,但结果好坏参半。我知道 GridBagLayout 是非常灵活且常用的 GUI,这是我一直在使用的。我什至尝试创建多个垂直框来表示列,并创建多个水平框来表示行,效果非常好,但最终未能给我所需的结果。
更具体地说,我的主要问题是,在下面的代码中,当我尝试将“输入 SQL 命令”列与左侧的文本字段框列对齐时,它不会像我需要的那样“浮动”到右侧相反,它会移动它下面的所有组件,从而弄乱定位。
如果有人能帮助指导我做错了什么,以及如何完成如下所示的 GUI,我将不胜感激。
到目前为止我的 Java 代码:
public class Methods extends JFrame{
private final JTextField item1 = new JTextField(40);
private final JTextField item2 = new JTextField(40);
private final JTextField item3 = new JTextField(40);
private final JTextField item4 = new JTextField(40);
private final JTextArea item5 = new JTextArea(6,30);
private JLabel label = new JLabel("Enter Database Information");
private JLabel label1 = new JLabel("JDBC Driver");
private JLabel label2 = new JLabel("Database URL");
private JLabel label3 = new JLabel("Username");
private JLabel label4 = new JLabel("Password");
private JLabel label5 = new JLabel("Enter a SQL Command");
private JLabel label6 = new JLabel("No Connection Now");
private JLabel label7 = new JLabel("SQL Execution Result");
private final JButton button1 = new JButton("Connect");
private final JButton button2 = new JButton("Execute SQL Command");
private final JButton button3 = new JButton("Clear Command");
private final JButton button4 = new JButton("Clear Results");
private final JPanel jp;
public Methods(){
super("SQL Client GUI - MHZ");
item1.setText("JDBC Driver");
item2.setText("Datbase URL");
item3.setText("Username");
item4.setText("Password");
//GUI Gridlayout Layout
jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints grid = new GridBagConstraints();
grid.anchor = GridBagConstraints.BASELINE_TRAILING;
grid.gridx=0;
grid.gridy=0;
//column1
jp.add(label1, grid);
grid.gridy++;
jp.add(label2, grid);
grid.gridy++;
jp.add(label3, grid);
grid.gridy++;
jp.add(label4, grid);
grid.gridy=0;
grid.gridx++;
//col2
jp.add(item1, grid);
grid.gridy++;
jp.add(item2, grid);
grid.gridy++;
jp.add(item3, grid);
grid.gridy++;
jp.add(item4, grid);
grid.gridy=0;
grid.gridx++;
//col3
jp.add(label5, grid);
grid.gridy++;
jp.add(item5, grid);
grid.gridy++;
grid.gridx=0;
grid.gridy=4;
jp.add(button1,grid);
grid.gridx++;
jp.add(button2, grid);
grid.gridx++;
jp.add(button3, grid);
grid.gridx++;
jp.add(button4, grid);
add(jp);
}
}
下图是它的外观。