我正在用 Java 开发 GUI。我不知道如何为每个字段插入新行。有人能帮我解决这个问题吗?这是我的代码:
public class InsertPanel extends JPanel{
public InsertPanel() {
setBackground(Color.yellow);
setPreferredSize(new Dimension(540, 500));
JLabel isbnLabel = new JLabel("ISBN: ");
JTextField isbnTextFld = new JTextField(10);
JLabel authorLabel = new JLabel("Author: ");
JTextField authorTextFld = new JTextField(10);
JLabel titleLabel = new JLabel("Title: ");
JTextField titleTextFld = new JTextField(10);
JLabel priceLabel = new JLabel("Price: ");
JTextField priceTextFld = new JTextField(10);
JButton submitBtn = new JButton("Submit");
JTextArea textArea = new JTextArea(10, 30);
add(isbnLabel);
add(isbnTextFld);
add(authorLabel);
add(authorTextFld);
add(titleLabel);
add(titleTextFld);
add(priceLabel);
add(priceTextFld);
add(submitBtn);
add(textArea, BorderLayout.CENTER);
}
}
输出中的这些字段位于同一行。我希望他们看起来像
国际标准书号:
作者:
标题:
价格:
提交
文本区域:
非常感谢!
最佳答案
考虑使用GridBagLayout
也许像...
public class InsertPanel extends JPanel {
public InsertPanel() {
setBackground(Color.yellow);
setLayout(new GridBagLayout());
JLabel isbnLabel = new JLabel("ISBN: ");
JTextField isbnTextFld = new JTextField(10);
JLabel authorLabel = new JLabel("Author: ");
JTextField authorTextFld = new JTextField(10);
JLabel titleLabel = new JLabel("Title: ");
JTextField titleTextFld = new JTextField(10);
JLabel priceLabel = new JLabel("Price: ");
JTextField priceTextFld = new JTextField(10);
JButton submitBtn = new JButton("Submit");
JTextArea textArea = new JTextArea(10, 30);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
add(isbnLabel, gbc);
gbc.gridy++;
add(authorLabel, gbc);
gbc.gridy++;
add(titleLabel, gbc);
gbc.gridy++;
add(priceLabel, gbc);
gbc.gridx++;
gbc.gridy = 0;
add(isbnTextFld, gbc);
gbc.gridy++;
add(authorTextFld, gbc);
gbc.gridy++;
add(titleTextFld, gbc);
gbc.gridy++;
add(priceTextFld, gbc);
gbc.gridy++;
add(submitBtn, gbc);
gbc.gridx++;
gbc.gridy = 0;
gbc.gridheight = gbc.REMAINDER;
add(new JScrollPane(textArea), gbc);
}
}
参见How to Use GridBagLayout了解更多详情
关于java - 在 Java GUI 中为每个字段插入一个新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29619641/