LukasFun
LukasFun

Reputation: 229

How to draw any text using drawString() in Java

I'm getting into graphical stuff in Java and want to display text. As I've read, drawString() is the standard method for this. My code to draw the string is:

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

public class TextDisplay extends JPanel{
    public void paint(Graphics g) {
        g.drawString("My Text", 10, 20);
    }
}

The class executing this is:

import javax.swing.*;

public class Main {
    public static void main(String[] args) {
        TextDisplay d = new TextDisplay();
        JFrame f = new JFrame();
        f.getContentPane().add(d);
        f.setSize(200,200);
        f.setVisible(true);
    }
}

This produces a window with the text "My Text" in it as expected. The question now is: How can I draw any String? With this I have to write the String into the paint() method, but I want to input it from somewhere else as a variable.

Upvotes: 0

Views: 17625

Answers (1)

WJS
WJS

Reputation: 40047

Don't use paint() or draw directly into a JFrame. Draw into a JPanel and override paintComponent(). To draw a specific String, store it in an instance field and then call repaint(). You may also want to examine LineMetrics and FontMetrics to be able to properly center the string.

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawString(mystring, x, y);
}

Check out The Java Tutorials for more on painting.

Upvotes: 1

Related Questions