Button Animation

D

Dancing Fingers

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
 
J

John B. Matthews

Dancing Fingers said:
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);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,772
Messages
2,569,593
Members
45,112
Latest member
VinayKumar Nevatia
Top