Question

The setBounds methods works fine if it's not in a for loop but the moment I place it in a for lopp it seizes to work why is this?

btnResize.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {

            //This re sizes the JButton.
            btnResize.setBounds(10, 11 ,100, 100);

            //This does nothing
            for(int i = 0; i < 500; i ++) {
                btnResize.setBounds(i, i , i, i);
            }

        }
    });
Was it helpful?

Solution

You're doing this in the UI thread, which means nothing in the UI has a chance to react to it until the loop has finished... only the last setBounds call will really have any visible effect.

If you're trying to perform animation, you'll need to use a timer of some description so that you can repeatedly make a small change, wait (without blocking the UI thread) and then make another change etc. (You probably don't want to use setBounds for that anyway, but that's a slightly different matter.) Note that you still need to make the changes on the UI thread, as they're UI changes - you just need to let the UI react to the change before you make the next one.

See the tutorial on Swing timers for more information and examples.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top