gpt4 book ai didi

java - JLabel 移动到坐标

转载 作者:行者123 更新时间:2023-12-01 14:34:52 27 4
gpt4 key购买 nike

让 JLabel 自动移动到坐标位置的最佳方法是什么?是否有针对此类任务的预定义方法?

示例:代替 label.setLocation(x + 1, y + 1); (重新运行移动)就像是:示例:label.moveTo(500, 500);或者找到最佳路径/路线的方法?

我读过有关 Oracle 的 java 文档,但找不到类似的内容。

最佳答案

这是在一段时间内将 JLabel 从一个位置移动到另一个位置的基本示例。

这是一个基于时间的动画,这意味着动画的速度取决于您希望动画播放的时间。物体需要移动的距离也会影响速度。

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MoveLabel {

public static void main(String[] args) {
new MoveLabel();
}

public MoveLabel() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public static class TestPane extends JPanel {

protected static final int PLAY_TIME = 4000;

private JLabel label;
private int targetX;
private int targetY;
private long startTime;
private final int startX;
private final int startY;

public TestPane() {
setLayout(null);
label = new JLabel("Testing");
label.setSize(label.getPreferredSize());
add(label);

Dimension size = getPreferredSize();

startX = 0;
startY = 0;

targetX = (size.width - label.getSize().width) / 2;
targetY = (size.height - label.getSize().height) / 2;

Timer timer = new Timer(40, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int x = label.getX();
int y = label.getY();
long duration = System.currentTimeMillis() - startTime;
float progress = (float)duration / (float)PLAY_TIME;
if (progress > 1f) {
progress = 1f;
((Timer)(e.getSource())).stop();
}

x = startX + (int)Math.round((targetX - startX) * progress);
y = startY + (int)Math.round((targetY - startY) * progress);

label.setLocation(x, y);
}
});
startTime = System.currentTimeMillis();
timer.start();
}

@Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
}
}

关于java - JLabel 移动到坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16577415/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com