From: Dancing Fingers on
Hi guys,
Does anyone know if there's an easy way to animate button that move
over time? I'm thinking:
about using LayoutManager, creating mock buttons, emptying
LayoutManager, animating the mock buttons, using LayoutManager again
and deleting the mock buttons. This seems like a lot of work to get
from point A to Point B? Any advice would be appreciated.
Chris
From: John B. Matthews on
In article
<6ab59a66-ccda-4c67-9cc3-bcadb16cae1d(a)g19g2000yqc.googlegroups.com>,
Dancing Fingers <batymahn(a)gmail.com> wrote:

> Does anyone know if there's an easy way to animate button that move
> over time? I'm thinking: about using LayoutManager, creating mock
> buttons, emptying LayoutManager, animating the mock buttons, using
> LayoutManager again and deleting the mock buttons. This seems like a
> lot of work to get from point A to Point B? Any advice would be
> appreciated.

You can use a layout manager to establish the initial geometry and then
do setBounds() to move the button(s). Try resizing the window in the
example below both with and without a subsequent null layout.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

/** @author John B. Matthews */
public class ButtonTest extends JPanel implements ActionListener {

private static final Random rnd = new Random();
private final Timer timer = new Timer(500, this);
private final List<JButton> buttons = new ArrayList<JButton>();

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
new ButtonTest().create();
}
});
}

private void create() {
JFrame f = new JFrame("ButtonTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
timer.start();
}

public ButtonTest() {
super(new GridLayout(5, 2));
this.setPreferredSize(new Dimension(640, 480));
for (int i = 0; i < 10; i++) {
JButton b = new JButton(String.valueOf(i));
buttons.add(b);
this.add(b);
}
}

@Override
public void actionPerformed(ActionEvent e) {
for (JButton b : buttons) {
Rectangle r = b.getBounds();
r.setBounds(
rnd.nextInt(getWidth() - r.width),
rnd.nextInt(getHeight() - r.height),
r.width, r.height);
b.setBounds(r);
}
}
}

--
John B. Matthews
trashgod at gmail dot com
<http://sites.google.com/site/drjohnbmatthews>