gpt4 book ai didi

java - 用随机颜色更新小程序

转载 作者:行者123 更新时间:2023-12-01 21:41:46 27 4
gpt4 key购买 nike

我正在尝试制作一个背景随时间缓慢变化的 JFrame。这是我的代码:

public class RainbowWindow extends Applet implements ActionListener {

private static final long serialVersionUID = 1L;

public void paint(Graphics g) {
Timer timer = new Timer(1000, this);
timer.start();
}

@Override
public void actionPerformed(ActionEvent e) {
Color color = new Color(((int) Math.random()), ((int) Math.random()), ((int) Math.random()), 255);
setBackground(color);

}
}

但我得到的只是黑屏

最佳答案

  1. Java Plugin support deprecatedMoving to a Plugin-Free Web
  2. 不要在paint中创建Timer,每次需要绘制组件时都会调用paint,并且通常会快速连续地调用。请参阅Painting in AWT and Swing nd Performing Custom Painting有关 Swing 中绘画工作原理的更多详细信息
  3. 您应该避免重写顶级容器(如 JFrame 和 Applet)的 Paint ,它们不是双缓冲的,并且往往会导致问题结束了,最好从某种组件开始并将其添加到您想要的任何容器
  4. JFrame != Applet
  5. Math.random 返回 01 之间的值,Color 期望 之间的值0-255

例如

import java.awt.Color;
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.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

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

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

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

public class TestPane extends JPanel {

public TestPane() {
Timer timer = new Timer(1000, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int red = (int)(Math.random() * 255);
int green = (int)(Math.random() * 255);
int blue = (int)(Math.random() * 255);
Color color = new Color(red, green, blue, 255);
setBackground(color);
}
});
timer.start();
}

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

}
}

关于java - 用随机颜色更新小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36367143/

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