简体   繁体   中英

Why do buttons go off screen on Flow Layout?

I'm learning flow layout from Head First Java and I'm trying to have buttons wrap around as it says a Flow Layout should (left to right, top to bottom).

import javax.swing.*;
import java.awt.*;
public class Flow {
    public static void main(String[] args) {
        Flow gui = new Flow();
        gui.go();
    }
    public void go() {
        JFrame frame = new JFrame();
        JPanel panel = new JPanel();

        JButton buttonOne = new JButton("hello");
        JButton buttonTwo = new JButton("this is");
        JButton buttowThree = new JButton("woody");

        panel.add(buttonOne);
        panel.add(buttonTwo);
        panel.add(buttonThree);

        frame.getContentPane().add(BorderLayout.EAST, panel);
        frame.setSize(200,200);
        frame.setVisible(true);
    }
}

However, when setting the panel on the EAST region of the frame, the buttons go off the screen and don't wrap around. If I set the panel on the NORTH or SOUTH region, I only see two buttons. If I set the panel on the CENTER region, they DO wrap and can see all of them clearly. Why is this?

If you're adding a component to a BorderLayout frame, the East and West regions will let the component get its preferred width. Since the panel contains three buttons and places them side by side, the preferred width of the panel is that of the three buttons side by side. Therefore, it is going "off-the-screen" since that is the preferred width. If you were to a button on to the frame on the EAST region instead and fill it up with enough text, the same would happen.

The CENTER region gets whatever is left that the other regions haven't taken up already. Since that is the policy of the CENTER region, the panel does NOT get its preferred width or height, therefore forcing the components of the panel to wrap.

As far as the NORTH and SOUTH regions go, the panel will get its preferred height which is the height of the tallest component (in the example all buttons are the same height). Therefore it sees no reason to wrap. The panel however, DOESN'T get its preferred width. Therefore the buttons are "cut off" since the max width the panel can have is that of the frame. You will notice as the frame resizes, the buttons appear on the screen as space is made available on the panel.

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