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.

LukasFun
  • 171
  • 1
  • 4
  • 17
  • 2
    just have it as an instance variable? – Azrael Oct 04 '19 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. – LukasFun Oct 04 '19 at 16:23
  • no, I mean an instance variable. you cant change the signature of paint(Graphics) and still expect it to work – Azrael Oct 04 '19 at 16:24

1 Answers1

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.

WJS
  • 36,363
  • 4
  • 24
  • 39