I am going to keep this discussion fairly abstract initially in hopes that I will get a broad range of approaches. Here goes...

I am working on an application which uses paint() to fill a JFrame with a "background" (a game table) and several ancillary elements (table markings, chips, etc.) At some point in the game, there will be a stack of chips on the table. Since the user cannot actually pick up and count the chips, I would like to display that value in a "text box" so the user can quickly see the number of chips in the stack.

This "text box" should have yellow text with a dark red background. The boundary for background should be just slightly larger than the text being displayed. I want to be able to specify the font style and I want to locate the box just slightly below the stack of chips.

I thought about a JLabel, but it might not be flexible enough to do what I want. I am also considering JTextField. I have tried experimenting with these, but I am running into problems with paint(). I need to figure out how to get the "text box" to the top of the "z order". So far, I cannot get it to display on top of the painted elements of the game table.

Thoughts? Suggestions?

I have code written, but it needs lots of PNG images to work and I didn't think that would be much fun for anyone.

Thanks,
Tahoe

Recommended Answers

All 3 Replies

There shouldn't be any problem doing this with a JLabel. You can set the size, fg/bg colours (including transparent background), font, style and point size etc. You can position it wherever you like by using a null LayoutManager. It will automatically display on top of the JFrame.
You may have a problem because you are using paint(Graphics g) and are not handling the painting of child objects properly. The recommended practice is always to override paintComponent(Graphics g) instead.

As JamesCherrill says, a JLabel should work. But you can also draw rectangles and strings with your Graphics object. You can paint both whatever color you choose and position them wherever you choose. Look up fillRect and drawString in the documentation for the Graphics class. Note that you can base the width of your rectangle on the length of the string so that it fits nicely in the background of the string. Also note that you first set color, font, etc. on the Graphics object and then you draw your rectangle or string. The draw (or fill) methods will use the current font, color, etc. when drawing.

Another option would be to create a small ChipStack class that extends JComponent and overrides paintComponent() to render both the stack of chips and the text count as a single graphical unit. It would make positioning on your table a tad easier.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.