I have an applet that's only purpose is to create a box and each time it's painted it changes color. Right now it is not changing color at all, it simply creates a random background color to start and sticks with it whenever painted but I need it to change. Any help on what I'm doing wrong would be appreciated.
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);
}
You've basically broken the paint chain, nothing is actually painting your background color...
You could do something like...
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);
}
But this will set up a infinite cycle of repaint requests which will eventually consume your CPU cycles and make you PC unusable (not to mention flicker like crazy)...
A better solution might be to override the getBackgroundColor
method...
@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;
}
This will mean that each time this method is called, it will generate a random color. You can then use, some other process, to force the applet to repaint...
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다