Type writer.

Heya,

Im trying to have a typewriter effect in my game. I could do it using the Java2D api but i found it was easier to use the JLabel since it supports html, and thus it would be easier to format things.

It works fine with a normal colid color background. But when i change the background of my frame to an image, the JLabel acts up. Its transparent for the most part, but whenever i change the text of the JLabel it flashes black ( also the color of the foreground if it helps )

Anybody know how to solve this problem, OR a better way to have like a type writer effect in your game?

Thanks in advanced

The easiest way would be a Timer or something like that.


// pseudo
String myText = "Hello World";
StringBuilder buffer = new StringBuilder();
Timer timer = new Timer(500);
int index = 0;

timer.addAction(new TimerAction() {
   public void perform() {
      if (buffer.length() < myText.length()) {
         buffer.append(myText.getCharAt(index));
         index += 1;
      }
   }
});

public void update(int deltaInMS) {
   timer.update(deltaInMS);
}

public void render(Graphics2D g) {
   g.drawString(10, 10, buffer.toString());
}

I know how to do the typewriter code, i already had it working when i posted, i just didnt like the ENTIRE JLabel flashing black everytime i changed its text value, and wanted to know if anyone knew a work around this.

I guess ill just do the g2d route. But that means i have to write code to wrap the text and perhaps for formatting, which is gonna be a hassle.

Share some code. It’s little use to say: “I tried this and that, and it doesn’t work!” :wink:

Perhaps it could work if you render the JLabel to an offscreen image first, and then draw that image to your backbuffer using Java2D?

JComponents are supposed to be double buffered, so it should not be required to render it to yet another buffer.

Chances are he’s calling setText() from the wrong thread, or he is using a Frame instead of a JFrame, overridden JLabel paintComponent to remove the background, without calling setOpaque(false), or many, many other things, as Swing is just a can of worms sometimes.

You’re right, and these are things to perhaps check first, but after 2.5 year of intensive swing programming at my day job I have to say that sometimes things can behave a bit unpredictable even if you did everything how you’re supposed to do. For example I recently had to change my code to update a swing component explicitly outside of the EDT to make it behave as desired. I know exactly why I had to do that, but it’s not something one would pick up from a swing tutorial.
But still, yes you’re right, check threading and such first before resorting to workarounds.

So GMaker0507, post some code.