Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Displaying random numbers. Java, AWT, drawString, GUI, Threads, Game&#

$
0
0
I am trying to display random numbers as part of a GUI in an applet based maths game, and have run into an issue. Either one of two things happen depending on from where I call the display method:

  • The numbers generate and display properly, without automatically updating each frame but get drawn over by the background and artwork each frame as they're being updated at runtime, or...
  • The number displayed on-screen appear above the background elements but are redrawn fresh every frame.


The ideology is that a randomly generated math question will be displayed on-screen in the format "6 x ? = 12" and remain there until the user shoots the correct answer. The sprite collision between the bullet and the icon representing the right number will then trigger the function to be recalled and a new question will be displayed, and the cycle repeats. (Its for some local school kids - to help them with their times tables! :))

Quick illustration:

private int setNumberOne() {

    return rand.nextInt(11) + 2;
}

private int setNumberTwo() {

    return rand.nextInt(11) + 2;
}

private int setAnswer() {

    return setNumberTwo() * setNumberOne();
}

private void displayOutput() {

    Graphics2D g2d = graphics();

    int one = setNumberOne();
    int ans = setAnswer();

    setNumberTwo();

    g2d.setColor(Color.WHITE);
    g2d.drawString(one + " x ? = " + ans, 480, 480);
}

Calling this function in the initialisation method displays a static question that I can update elsewhere when specific triggers are met, however everything else gets drawn on top of it by the update event, rendering it invisible. The only way I've managed to see this working is to remove the other images from the game for testing.

Is there a way to set the "precedence" of GUI elements in an applet?

I also tried to not allow the background to update at runtime, but the result was that the moving game objects left trails all over the screen.

What am I missing? If anyone has any suggestions as to how this can be correctly implemented, I'd be delighted to hear them. I believe the issue is something to do with drawString, but don't know for certain. Either way I don't know how to replace it correctly.

Other things I've looked at include JLabels and AlphaComposites, Lightweights and super.paint(), separate threads for the display method... but I'm truly stuck because I can't get anything to work!

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>