我对java相当陌生,所以我认为我对此不太接近,但我似乎可以找到任何其他帮助。基本上,我正在尝试对 jPanel 的背景颜色进行动画处理,以便它的色调(我正在使用 hsb 颜色模型)发生变化。有点像这样:https://kahoot.it/#/注意颜色是如何从一种颜色 float 到另一种颜色的。这是我到目前为止的代码:
public void animate(){
for(float i=.001f;i<1f;i+=.001f){
jPanel1.setBackground(Color.getHSBColor(i, .53f, .97f));
try{
Thread.sleep(5L);
}catch(InterruptedException ex){
}
System.out.println(i);
}
}
现在我知道这可能是不对的,但是循环工作正常,唯一的问题是 jPanel 在循环完成之前不会“更新”。抱歉,我对此类事情是个大菜鸟,感谢您的回复
最佳答案
问题是您阻塞了事件调度线程,因此无法进行绘制。使用 Swing Timer而不是 sleep 。更改 HSB 颜色的运行示例:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class ColorCycle {
private static class ColorPanel extends JPanel {
private final float stepSize;
private final Timer timer;
private int index;
ColorPanel(final int steps, int fps) {
stepSize = 1f / steps;
timer = new Timer(1000 / fps, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
index++;
if (index > steps) {
index = 0;
}
repaint();
}
});
}
void start() {
timer.start();
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.getHSBColor(index * stepSize, 1f, 1f));
g.fillRect(0, 0, getWidth(), getHeight());
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame("Colors");
ColorPanel panel = new ColorPanel(300, 20);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.pack();
frame.setVisible(true);
panel.start();
}
});
}
}
关于java - 使用 hsb 模型 Java 制作背景颜色动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22274259/