简体   繁体   English

如何按行制作布局?

[英]How do I make the layouts in rows?

I am trying to make the layout stabilized and fixed. 我正在尝试使布局稳定和固定。 When I resized the window, it gives me just one line instead of an actual row layout. 当我调整窗口大小时,它只给我一行而不是实际的行布局。 How do I make the layout neat? 如何使布局整洁?

Here is my code: 这是我的代码:

class BookstoreFrame extends JFrame
{
   JButton btnSubmit;
   JTextField txtISBN, txtTitle, txtAuthor, txtPrice;
   JLabel lblISBN, lblTitle, lblAuthor, lblPrice;
   int count = 0;

   public BookstoreFrame(String title)
   {
      FlowLayout layout = new FlowLayout(FlowLayout.CENTER, 5, 20);
      setLayout(layout);

      lblISBN = new JLabel("ISBN: ");
      txtISBN = new JTextField(10);
      lblTitle = new JLabel("Book Title: ");
      txtTitle = new JTextField(10);
      lblAuthor = new JLabel("Author: ");
      txtAuthor = new JTextField(10);
      lblPrice = new JLabel("Price: ");
      txtPrice = new JTextField(10);

      btnSubmit = new JButton("Submit");
      add(lblISBN);
      add(txtISBN);
      add(lblTitle);
      add(txtTitle);
      add(lblAuthor);
      add(txtAuthor);
      add(lblPrice);
      add(txtPrice);
      add(btnSubmit);
      btnSubmit.addActionListener(new seeTextBookInfo());
   }
}

You are using FlowLayout, it adds the components in one direction until there is no more space and then creates a new line. 您正在使用FlowLayout,它将在一个方向上添加组件,直到没有更多空间,然后创建新行。

You could use BoxLayout, to add the elements from left to right: https://docs.oracle.com/javase/8/docs/api/javax/swing/BoxLayout.html 您可以使用BoxLayout从左到右添加元素: https : //docs.oracle.com/javase/8/docs/api/javax/swing/BoxLayout.html

BoxLayout layout = BoxLayout(this, BoxLayout.X_AXIS);

How do I make the layout neat? 如何使布局整洁?

We have no idea what "neat" means to you? 我们不知道“整洁”对您意味着什么?

Typically you would have label/text field pairs on a single row, then maybe the button on its own row. 通常,您将在一行上放置标签/文本字段对,然后在其自己的行上放置按钮。

I would suggest you might want to use the GridBagLayout as it allows you to have flexible row and column grids for your components. 我建议您可能要使用GridBagLayout因为它允许您为组件提供灵活的行和列网格。

The basic code might be something like: 基本代码可能类似于:

setLayout( new GridBagLayout() );
GridBagConstraints gbc = new GridBagConstraints();

gbc.gridx = 0;
gbc.gridy = 0;
add(lblISBN, gbc);

gbc.gridx = 1;
add(txtISBN, gbc);

gbc.gridx = 0;
gbc.gridy = 1;
add(lblTitle);

gbc.gridx = 1;
add(txtTitle);

... // add other components here

gbc.gridx = 0;
gbc.gridy = ?;
gbc.gridwidth = 2;
gbc.anchor = ???
add(btnSubmit);

Read the section from the Swing tutorial on How to Use GridBagLayout for more information and examples to get you started. 阅读Swing教程中有关如何使用GridBagLayout的部分,以获取更多信息和示例,以帮助您入门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM