The moose likes Swing / AWT / SWT and the fly likes Bug in SpringLayout ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Bug in SpringLayout ? " Watch "Bug in SpringLayout ? " New topic

Bug in SpringLayout ?

Mariusz Malinowski

Joined: Dec 15, 2004
Posts: 14

Once again I post the topic. This time with shortened code.

Whenever I press a button (see my code below) the execution time of my app increases (if run my app, please press the button at least 5 times). Has anyone encountered such a problem when using SpringLayout?

If I change layout the app works fine.
I would grateful for any suggestions.


package problem;
import java.awt.Container;
import java.awt.event.*;
import javax.swing.*;

public class SpringProblem implements ActionListener {

JButton button;
JPanel panel;
int rows;

private SpringProblem(){
JFrame frame = new JFrame();
Container c = frame.getContentPane();
c.add(new JScrollPane(labelPanel(40)), "Center");
c.add(button = new JButton("Add"), "South");

private JPanel labelPanel(int labelCounter){
panel = new JPanel(new SpringLayout());
for (int i = 0; i < labelCounter; i++) panel.add(new JLabel("OLD"));
// 10 refers to the number of columns
rows = labelCounter/10;
SpringUtilities.makeCompactGrid(panel, rows, 10, 10, 10, 5, 5);
return panel;

public void actionPerformed(ActionEvent arg0) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
for (int i = 0; i < 10; i++) panel.add(new JLabel("NEW"));
SpringUtilities.makeCompactGrid(panel, rows, 10, 10, 10, 5, 5);
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable(){
public void run() {
new SpringProblem();
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

If you press the button 5 times, there will be 90 labels. Why does it surprise you that laying out a container takes longer the more components are in it? Especially given that SpringLayout works by defining relationships between components, even quadratic performance in the number of components wouldn't be a big surprise.

Another layout manager like, say, GridLayout would handle this very differently: it forces all the components to be the same size, which it computes without asking any of them its preferred dimensions -- so it's obviously going to be much faster!

[Jess in Action][AskingGoodQuestions]
Mariusz Malinowski

Joined: Dec 15, 2004
Posts: 14
First of all thank you for your answer.

I checked what it would be if I change initial number of displayed labels:

c.add(new JScrollPane(labelPanel(140)), "Center");

In the result it turned out that panel with 150 labels (initial value 140) appears faster than panel with 90 labels (initial value 40).

That's the thing which makes me wonder.


I agree. Here's the link:
subject: Bug in SpringLayout ?
It's not a secret anymore!