gpt4 book ai didi

java - JPanel 平滑运动并同时更新 JLabel

转载 作者:行者123 更新时间:2023-12-02 10:01:46 24 4
gpt4 key购买 nike

如何让JPanel平滑移动并同时更新JLabel

我想在 JFrame 上显示当前时间,因此我创建了一个新的 java.util.Timer 并每隔一秒更新一次标签。

我还创建了另一个 Java 线程来移动面板组件。

但是当移动面板并在框架上显示(更新)时间时,面板刷新以形成原始位置。

所以我在 Google 中搜索该问题,但找不到解决方案。

//Code to move jPanel smoothly
Thread t = new Thread(){
int i = 0 ;
public void run(){
while(i<150){
i++;
jPanel2.setLocation(i, jPanel2.getY());
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
}
}
};
t.start();

// Code to show Time
Timer t = new javax.swing.Timer(1, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
jLabel1.setText(new Date()+"");
}
});
t.start();

最佳答案

这是一个小示例,如何为组件提供动画和更新。

import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;

/**
* <code>MovedClock</code>.
*/
public class MovedClock {

private final JLabel clock = new JLabel();
private final DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm:ss");

private void startUI() {
JFrame frame = new JFrame("Moved clock");
frame.setLayout(null); // usually it's a bad idea, but for animation we need this.
clock.setBounds(0, 50, 50, 20);
frame.add(clock);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 200);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
updateClock();
Timer clockTimer = new Timer(1000, e -> updateClock());
clockTimer.start();
// 15 milliseconds for about 60fps
Timer moveTimer = new Timer(15, new ActionListener() {

private int count = 1;

private int increment = 1;

@Override
public void actionPerformed(ActionEvent e) {
if (count == 435 || count == 0) {
increment = -increment;
}
Point loc = clock.getLocation();
loc.x += increment;
clock.setLocation(loc);
count += increment;
}
});
moveTimer.start();
}

private void updateClock() {
clock.setText(LocalTime.now().format(format));
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new MovedClock()::startUI);
}
}

关于java - JPanel 平滑运动并同时更新 JLabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55568558/

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