简体   繁体   中英

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.

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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