Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to draw String with background on Graphics?

Tags:

java

swing

I draw texts with Graphics.drawString but I want to draw Strings with rectangle background.

like image 552
bobby Avatar asked Jun 20 '11 19:06

bobby


2 Answers

Use Graphics.fillRect or Graphics2D.fill before drawing the text.

Here's an example:

import java.awt.*;
import java.awt.geom.Rectangle2D;
import javax.swing.*;

public class FrameTestBase extends JFrame {
    public static void main(String args[]) {
        FrameTestBase t = new FrameTestBase();
        t.add(new JComponent() {
            public void paintComponent(Graphics g) {
                String str = "hello world!";
                Color textColor = Color.WHITE;
                Color bgColor = Color.BLACK;
                int x = 80;
                int y = 50;

                FontMetrics fm = g.getFontMetrics();
                Rectangle2D rect = fm.getStringBounds(str, g);

                g.setColor(bgColor);
                g.fillRect(x,
                           y - fm.getAscent(),
                           (int) rect.getWidth(),
                           (int) rect.getHeight());

                g.setColor(textColor);
                g.drawString(str, x, y);
            }
        });

        t.setDefaultCloseOperation(EXIT_ON_CLOSE);
        t.setSize(400, 200);
        t.setVisible(true);
    }
}

enter image description here

like image 143
aioobe Avatar answered Nov 06 '22 21:11

aioobe


Suggestion:

  • Use a JLabel
  • Set its opaque property to true via setOpaque(true);
  • Set its foreground color via setForeground(myForegroundColor);
  • Then set its background color via setBackground(myBackgroundColor);
like image 20
Hovercraft Full Of Eels Avatar answered Nov 06 '22 21:11

Hovercraft Full Of Eels