0

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.

3
  • 2
    just have it as an instance variable? Commented Oct 4, 2019 at 16:20
  • You mean like paint(Graphics g, String s)? If so, where would this String come from? My main program never actually calls this method. Commented Oct 4, 2019 at 16:23
  • no, I mean an instance variable. you cant change the signature of paint(Graphics) and still expect it to work Commented Oct 4, 2019 at 16:24

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.