我正在使用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);
}
}
输出中的那些字段位于同一行。我希望他们看起来像
ISBN:
作者:
名称:
价格:
提交
的TextArea:
非常感谢!
答案 0 :(得分:2)
考虑使用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