需要调整窗口大小以使程序正常工作



这是我的Layout类的代码。

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Layout extends JFrame {
    private JButton lb;
    private JButton cb;
    private JButton pb;
    private FlowLayout layout;
    private Container container;
    public Layout() {
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);
        //*Left
        lb = new JButton("L");
        add(lb);
        lb.addActionListener(
            new ActionListener(){   
                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.LEFT);
                    layout.layoutContainer(container);
                }
            }
        );
        //*Center
        cb = new JButton("C");
        add(cb);
        cb.addActionListener(
            new ActionListener(){   
                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            }
        );      
        //*Right
        pb = new JButton("R");
        add(pb);
        pb.addActionListener(
            new ActionListener(){   
                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            }
        );
    }
}

我正在通过youtube上的newpost教程学习java(这段代码来自本教程)。但这一个不起作用。当我单击右侧按钮(R)时,它应该会立即将所有按钮拖动到窗口的右侧。事实并非如此。然而,当我点击右键,然后强制调整窗口大小时,它会做它应该做的事情。通过在主方法中添加setResizable(false),我无法调整程序的大小,所以它不起作用。我做错了什么?

请原谅我英语不好。

替换

container = new Container();

通过

container = getContentPane();

最简单的方法是设置一个新的FlowLayout并调用invalidate():

    setLayout(new FlowLayout(FlowLayout.LEFT));
    invalidate();
    validate();

更新当前FlowLayout无效。

最新更新