Here is the code of my Layout class.

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);
                }
            }
        );
    }
}

I'm learning java through thenewboston youtube tutorials (this code is from this tutorial). But this one doesn't work like it should. When I click the right button (R) it should drag all the buttons to the right side of the window instantly. It doesnt. However when I click that right button and then forcibly resize the window then it do what it should. By adding setResizable(false) in the main method I cant resize the program so it doesnt work. What have I done wrong?

Forgive me for my poor English btw.

有帮助吗?

解决方案

replace

container = new Container();

by

container = getContentPane();

其他提示

The simplest way would be to set a new FlowLayout and call invalidate():

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

Updating the current FlowLayout has no effect.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top