Here is my code to draw image to screen:
public class Main extends Applet implements Runnable, KeyListener{
private URL base;
private Image image, image1,image2, image3, background;
private Graphics second;
String imageString;
@Override
public void init() {
setSize(800, 600);
setBackground(Color.BLACK);
setFocusable(true);
addKeyListener(this);
Frame frame = (Frame) this.getParent().getParent();
frame.setTitle("show image");
try {
base = getDocumentBase();
} catch (Exception e) {
}
background = getImage(base, "data/background.png");
image1 = getImage(base, "data/image1.png");
image2 = getImage(base, "data/image2.png");
image3 = getImage(base, "data/image3.png");
}
@Override
public void start() {
Thread thread = new Thread(this);
thread.start();
}
@Override
public void run() {
imageString = randomString();
repaint();
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
second = image.getGraphics();
}
second.setColor(getBackground());
second.fillRect(0, 0, getWidth(), getHeight());
second.setColor(getForeground());
paint(second);
paint(g);
g.drawImage(image, 0, 0, this);
}
public void paint(Graphics g) {
g.drawImage(background, 0, 0, this);
if (imageString == "color of green"){
g.drawImage(image1, 0, 0, this);
} else if (imageString == "red of color"){
g.drawImage(image2, 0, 0, this);
} else if (imageString == null){
g.drawImage(image3, 0, 0, this);
}
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
}
@Override
public void keyPressed(KeyEvent e) {
}
public String randomString(){
int randNum;
String randString = null;
String randString1 = null;
randNum = (int)(Math.random()*2 + 1);
if (randNum == 1){
randString = "color";
randString1 = "green";
} else if (randNum == 2){
randString = "red";
randString1 = "color";
}
return randString + " of " + randString1;
}
}
Nothing is drawn on the screen, why? I believe its not recognizing "randString + " of " randString1" because if I made it return randString only, and set my "if statements" in my paint (Graphics g), it works, but this code does not... why?
Thanks!