简体   繁体   中英

What is the purpose of `setLayout` method in Swing/AWT components?

public void frame_pizza() {
        pizzaMenu.setVisible(true); //makes Jframe pizzaMenu visible
        pizzaMenu.setSize(1300, 750); //set size of Jframe pizzaMenu of width 1300 pixels and height 750 pixels
        pizzaMenu.setDefaultCloseOperation(EXIT_ON_CLOSE);//exit the application when close button (X) is clicked
        p2.setLayout(new GridBagLayout());
        pizzaMenu.setLayout(new BorderLayout());
    }

What is the purpose of these 2 lines?

p2.setLayout(new GridBagLayout()); 
pizzaMenu.setLayout(new BorderLayout());

Java (Swing/AWT) uses something called LayoutManager s to place UI components on the screen. These LayoutManagers are responsible to render component such as TextField, CheckBox, etc in a predefined manner on your Window.

For example:

  • A LayoutManager called FlowLayout simply places components one after the other.
  • BorderLayout places components in specific sections of the window such as top(NORTH), bottom(SOUTH), left(WEST), right(EAST) and center(CENTER).
  • GridBagLayout is another Layout Manager that gives the developer more precise rendering of components.

In your question, the setLayout method is setting one of these Layout Manager to manage rendering of the pizzaMenu frame or p2 panel.

You should probably do learn how to use different Layout Managers in Java.

This is a good place to start.


Hope this helps!

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