【问题标题】:Java Applet Changed With PaintJava Applet 用 Paint 改变了
【发布时间】:2015-01-18 22:40:10
【问题描述】:

我有一个小程序,其唯一目的是创建一个盒子,每次绘制它都会改变颜色。现在它根本没有改变颜色,它只是创建一个随机的背景颜色来开始并在绘制时坚持使用它,但我需要它来改变。对我做错的任何帮助将不胜感激。

import java.applet.*;
import java.awt.*;
import java.util.*;

public class AppletSubClass2 extends Applet {
public void init() {
    System.err.println("Hello from AnAppletSubClass.init");
    setBackground(color);
}
public void paint(Graphics g) {
    System.err.println("Hello from .paint!This time the applet will change colors when painted");
    setBackground(new Color(randomNum1, randomNum2, randomNum3));
}
Random rand = new Random();
int randomNum1 = rand.nextInt(251);
int randomNum2 = rand.nextInt(251);
int randomNum3 = rand.nextInt(251);
Color color = new Color(randomNum1, randomNum2, randomNum3);
}

【问题讨论】:

标签: java applet awt


【解决方案1】:

你基本上已经打破了油漆链,实际上没有任何东西在绘制你的背景颜色......

你可以这样做......

public void paint(Graphics g) {
    int randomNum1 = rand.nextInt(251);
    int randomNum2 = rand.nextInt(251);
    int randomNum3 = rand.nextInt(251);
    Color color = new Color(randomNum1, randomNum2, randomNum3);
    setBackground(color);
    super.paint(g);
}

但这会设置一个无限循环的重绘请求,最终会消耗您的 CPU 周期并使您的 PC 无法使用(更不用说疯狂地闪烁)...

更好的解决方案可能是覆盖getBackgroundColor 方法...

@Override
public Color getBackground() {
    int randomNum1 = rand.nextInt(251);
    int randomNum2 = rand.nextInt(251);
    int randomNum3 = rand.nextInt(251);
    Color color = new Color(randomNum1, randomNum2, randomNum3);
    return color;
}

这意味着每次调用此方法时,都会生成一个随机颜色。然后,您可以使用其他一些过程来强制小程序重新绘制...

【讨论】:

  • 谢谢,这个想法确实可行,但是我无法想出一种方法来强制它重新绘制。我知道我基本上每次都必须“删除”颜色对象,并在每次调用它时创建一个新对象以获取新对象,但我不知道该怎么做。
  • 在小程序上致电repaint。你可以使用某种Timer 或背景Thread
【解决方案2】:

试试这个,因为我正在工作:

    setBackground(new Color(rand.nextInt(251), rand.nextInt(251), rand.nextInt(251)));

您的小程序不会改变颜色,因为在开始时定义了一个随机颜色,并且每次它都绘制 使用开头声明的相同随机颜色重新绘制。

希望对你有帮助

【讨论】:

  • 它的工作原理是随机改变颜色,但它会自动进行,而无需我最小化/最大化小程序。我认为仅在浏览器中重新绘制而不是自动调用paint时?
  • @user3587186 你认为setBackground 在做什么?每次调用它都会触发repaint 请求...但是您已经破坏了油漆链...
【解决方案3】:

这部分代码只运行一次,当您实例化 AppletSubClass2 对象时。

Random rand = new Random();
int randomNum1 = rand.nextInt(251);
int randomNum2 = rand.nextInt(251);
int randomNum3 = rand.nextInt(251);
Color color = new Color(randomNum1, randomNum2, randomNum3);

因此,此后对 repaint() 的每次调用都将使用相同的 randomNum1、randomNum2 和 randomNum3 值。

您可能想要的是一种在方法中生成随机颜色的方法:

public Color generateRandomColor() {
    Random rand = new Random();
    int randomNum1 = rand.nextInt(251);
    int randomNum2 = rand.nextInt(251);
    int randomNum3 = rand.nextInt(251);
    return new Color(randomNum1, randomNum2, randomNum3);
}

然后在 repaint() 中使用它:

public void paint(Graphics g) {
    setBackground(generateRandomColor());
}

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    • 2013-03-12
    • 1970-01-01
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多