user1074600
user1074600

Reputation:

Is there any way to draw outside of an Applet's paint() method?

I have an applet that I'm trying to paint but I want to do it outside of the applet's paint() method. Currently I have an Entity class which takes an image's filename and screen coordinates as arguments. The constructor makes a call to a Sprite class which handles resource loading and stuff like that.

So I have a class called MainMenuState which was originally supposed to handle keyboard input for the main menu of my applet (I'm working on a 2D game) but I realized that it would be better to put drawing code in there as well. What I want to do is draw the main menu background when the main menu state is constructed. Here's what I have so far:

Game.java (extends Applet)

public void init() {
    this.setSize(500, 500);

    // New games have the MainMenuState by default because the game starts at the main menu.
    setState(new MainMenuState(this));

    Entity background = new Entity("../Assets/Menus/titleScreen.png", 0, 0);
    background.draw(this.getGraphics());

}

MainMenuState.java (extends abstract State class)

public MainMenuState(Game game) {
    super(game);
    Graphics g = game.getGraphics();
    Entity background = new Entity("../Assets/Menus/titleScreen.png", 0, 0);
    background.draw(g);
}

The applet runs and the draw methods are all being called correctly but the applet never paints the image to the screen. Currently my applet's paint() method is empty. How can I draw images to the screen outside of the applet's paint() method?

Thanks.

Update: Alright. I modified my MainMenuState class to call the background's draw() method using the graphics context of an off-screen buffer, which I then paint to the screen. This works but I get flickering whenever I resize the window.

Game.java

public void init() {
    this.setSize(500, 500);

    offScreen = new BufferedImage(500, 500, BufferedImage.TYPE_INT_ARGB);
    graphics = offScreen.getGraphics();

    // New games have the MainMenuState by default because the game starts at the main menu.
    setState(new MainMenuState(this));
}

public void paint(Graphics g) {
    g.drawImage(offScreen, 0, 0, this);
}

public void update(Graphics g) {
    paint(g);
}

MainMenuState.java is the same except for this: background.draw(game.getOffScreenGraphics());

Update 2: Of course, do applets always flicker when they resize? That could be it.

Upvotes: 1

Views: 1023

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285460

Never use getGraphics() since the Graphics object obtained is never guaranteed to persist. I suggest that you draw in a BufferedImage if you want to draw "outside of paint", and then draw that image inside of the paint method when you wish to display it. To display something it must eventually be drawn in the paint method, period.

Upvotes: 1

Related Questions