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);
}
});
}
}
Validate & repaint the visible part of the frame, i.e. the ContentPane
getContentPane().revalidate();
getContentPane().repaint();