2

When I change a property of a layout manager of a component which is currently visible in SWING the changes are not made visible. If I resize the entire frame the changes get visible.

How to solve this problem? I've experimented with revalidate() and friends but without any success. Also a LayoutFun.this.revalidate(); after the line where the property of the layout is changed (mgr.setAlignment(align);) does not help any.

Short selfexplaining example - when you press the button it's alignment should change. Instead nothing happens (on my computer) and only if I resize the entire frame the changes get visible.

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

public class LayoutFun extends JFrame {

    public LayoutFun() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final FlowLayout mgr = new FlowLayout(FlowLayout.CENTER);
        setLayout(mgr);
        add(new JButton(new AbstractAction("Other alignment") {

            @Override
            public void actionPerformed(ActionEvent e) {
                int align = mgr.getAlignment();
                switch (align) {
                    case FlowLayout.CENTER:
                        align = FlowLayout.LEFT;
                        break;
                    case FlowLayout.LEFT:
                        align = FlowLayout.RIGHT;
                        break;
                    default:
                    case FlowLayout.RIGHT:
                        align = FlowLayout.CENTER;
                        break;
                }
                mgr.setAlignment(align);
            }
        }));
    }

    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                LayoutFun lst = new LayoutFun();
                lst.setVisible(true);
                lst.setSize(600, 400);
            }
        });
    }
}
Rhangaun
  • 1,430
  • 2
  • 15
  • 34
mythbu
  • 786
  • 1
  • 7
  • 20

1 Answers1

3

Validate & repaint the visible part of the frame, i.e. the ContentPane

getContentPane().revalidate();
getContentPane().repaint();
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • This works. Amazing. But what when I'm not directly inside a JFrame. Let's say I get a `Container` and call `((FlowLayout) container).setAlignment(align);` on the container? `getContentPane()` does not exits than. – mythbu Apr 27 '15 at 16:11
  • Not so simple in my application. But your answer helped may anyway. – mythbu Apr 27 '15 at 16:26
  • with repaint() too,but with successs in most cases – mKorbel Apr 27 '15 at 16:26
  • @mythbu (re)validate with repaint are notifiers for LayoutManagers in already visible Swing GUI, – mKorbel Apr 27 '15 at 16:27
  • I finally got it with some casting and only using `getContentPane().revalidate();`. Thank you! – mythbu Apr 28 '15 at 11:34