Marte Engine TextEntity setColor()

I’ve been focusing on learning Java game development over the last couple of weeks. I’ve found that lwjgl, Slick2d, and Marte Engine are great libraries to help with the basic game functionality. In fact, they take a lot of the work out of it and leave you to focus on the game design itself. For instance, the Marte engine comes with a great resource manager class that helps keep up with images, sounds, and spritesheets for your game. Marte also has some good classes which extend Slick2D’s Entity class which can be very useful.

The one I’m going to focus on is TextEntity, which is great for adding text to the screen. However, I was unable to change the text color for the text directly using the setColor() method from the Entity class, which is inherited by TextEntity. There’s not a lot of documentation for either Slick2D or Marte, so I wasn’t exactly sure if I was missing something or if I had found a problem with the class.

Fixing the problem is rather simple. I created a new class called MyText and copied everything over from the TextEntity class. I could have extended it, but instead I wanted a new class which extends Entity directly. Then I changed the code in the render() method as such:

1
2
3
4
5
6
7
8
9
10
11
public void render(GameContainer container, Graphics g)	throws SlickException {
	if (font == null) {
		font = container.getDefaultFont();
		this.calculateHitBox();
	}
	g.setFont(font);
	if (text != null) {
		g.setColor(this.getColor());
		g.drawString(text, x, y);
        }
}

I then added a new constructor that takes a color as the fifth parameter:

1
2
3
4
5
6
public MyText(float x, float y, Font font, String text, Color color) {
	super(x,y);
	this.setColor(color);
	this.font = font;
	this.setText(text);
}

This gave me the functionality I was after. This change basically just sets the graphics object color property to the Entity’s color property, which is exactly how I thought it should have worked to begin with.

If there’s a better way to accomplish this, let me know. I’m only intermediate with Java.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.