Java 程序在 window 调整大小之前不会做出反应

Java program wont react till the window gets resized

我有一个简单的 java 程序,当我 运行 使用 eclipse 时,它​​会显示我为布局设置的 3 个 JButton。这些按钮设置为更改布局的对齐方式。所以你按左对齐左对齐,右对齐右对齐,居中对齐居中。

虽然按钮执行此操作,但在调整大小之前 window 中的对齐方式不会改变。

我已经尝试更新 jdk 和 eclipse,但没有什么不同,我看不出代码本身有问题。

有人知道这是为什么吗?

导入javax.swing.JFrame;

public class Main {
    public static void main(String []args){

        Layout_buttonsAndActionEvents layout = new Layout_buttonsAndActionEvents();

        layout.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        layout.setSize(300,300);
        layout.setVisible(true);



    }

}



import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

public class Layout_buttonsAndActionEvents extends JFrame {

    private static final long serialVersionUID = 1L;
    private JButton leftButton;
    private JButton rightButton;
    private JButton centerButton;

    private FlowLayout layout;
    private Container container;

    public Layout_buttonsAndActionEvents(){
        super("The Title");
        layout = new FlowLayout();
        container = new Container();
        setLayout(layout);


        leftButton = new JButton("Left");
        add(leftButton);
    //Align to the left
        leftButton.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent event){
                layout.setAlignment(FlowLayout.LEFT);
                layout.layoutContainer(container);
            }
        });


    centerButton = new JButton("Center");
    add(centerButton);

    //Align to the right
         centerButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.CENTER);
                    layout.layoutContainer(container);
                }
            });

         rightButton = new JButton("Right");
        add(rightButton);

        //Align to the right
            rightButton.addActionListener(new ActionListener(){

                public void actionPerformed(ActionEvent event){
                    layout.setAlignment(FlowLayout.RIGHT);
                    layout.layoutContainer(container);
                }
            });



    }


}

当您调整 JFrame 的大小时,它会使用新的大小和布局重新验证。同样,您必须在添加更改后的布局以应用视觉差异后验证并重新绘制框架。

确保在更改布局后按此顺序调用这些方法:

setLayout(layout);
repaint();
revalidate();

因为您要将按钮添加到 JFrame 的内容中 pane(通过 add() 方法,这实际上是对 getContentPane().add() 在幕后)你需要调用 revalidate() 内容窗格。

在三个动作侦听器中,更改:

    layout.setAlignment(FlowLayout.XXX);
    layout.layoutContainer(container);

至:

    layout.setAlignment(FlowLayout.XXX);
    getContentPane().revalidate();

此外,您可以删除对名为 'container' 的变量的所有引用,因为它在您的示例中没有任何作用。