我想创建一个程序,让Jframe能够自己自由移动。有点像翻译/转换。
例如,
-
单击程序开始。
-
Jframe在位置(0,0)处生成。
-
自动向右移动(设置动画)100个像素,使新坐标为(100,0)。
我知道有setLocation(x,y)方法可以在程序运行后设置初始位置,但有没有办法在程序启动后移动整个Jframe?
基本概念如下。。。
public class MoveMe01 {
public static void main(String[] args) {
new MoveMe01();
}
public MoveMe01() {
EventQueue.invokeLater(
new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Use the Force Luke"));
frame.pack();
frame.setLocation(0, 0);
frame.setVisible(true);
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Point location = frame.getLocation();
Point to = new Point(location);
if (to.x < 100) {
to.x += 4;
if (to.x > 100) {
to.x = 100;
}
}
if (to.y < 100) {
to.y += 4;
if (to.y > 100) {
to.y = 100;
}
}
frame.setLocation(to);
if (to.equals(location)) {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
}
}
这是一个非常直的线性动画。你最好研究Swing可用的众多动画引擎中的一个,这将使你能够根据当前帧更改动画的速度(例如,执行慢进和慢出等操作)
我会看看
- 时间框架
- 三叉戟
- Universla Tween引擎
更新了"可变时间"解决方案
这基本上是一个如何制作可变时间动画的示例。也就是说,您可以调整时间,并允许动画根据动画的运行时间计算移动要求,而不是固定的移动。。。
public class MoveMe01 {
public static void main(String[] args) {
new MoveMe01();
}
// How long the animation should run for in milliseconds
private int runTime = 500;
// The start time of the animation...
private long startTime = -1;
public MoveMe01() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
final JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new JLabel("Use the Force Luke"));
frame.pack();
frame.setLocation(0, 0);
frame.setVisible(true);
Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
// Start time of the animation...
startTime = System.currentTimeMillis();
}
// The current time
long now = System.currentTimeMillis();
// The difference in time
long dif = now - startTime;
// If we've moved beyond the run time, stop the animation
if (dif > runTime) {
dif = runTime;
((Timer)e.getSource()).stop();
}
// The percentage of time we've been playing...
double progress = (double)dif / (double)runTime;
Point location = frame.getLocation();
Point to = new Point(location);
// Calculate the position as perctange over time...
to.x = (int)Math.round(100 * progress);
to.y = (int)Math.round(100 * progress);
// nb - if the start position wasn't 0x0, then you would need to
// add these to the x/y position above...
System.out.println(to);
frame.setLocation(to);
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
});
}
}