Trying to use drawString method to print a name

John Dawson picture John Dawson · Dec 11, 2012 · Viewed 16.2k times · Source

I'm just going through some basic tutorials at the moment. The current one wants a graphics program that draws your name in red. I've tried to make a NameComponent Class which extends JComponent, and uses the drawString() method to do this:

import java.awt.Graphics2D;
import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JComponent;

public class NameComponent extends JComponent {

    public void paintMessage(Graphics g) {

    Graphics2D g2 = (Graphics2D) g;

    g2.setColor(Color.RED);
    g2.drawString("John", 5, 175);

    }
}

and use a NameViewer Class which makes use of JFrame to display the name:

import javax.swing.JFrame;

public class NameViewer {

public static void main (String[] args) {

    JFrame myFrame = new JFrame();
    myFrame.setSize(400, 200);
    myFrame.setTitle("Name Viewer");
    myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    NameComponent myName = new NameComponent();
    myFrame.add(myName);

    myFrame.setVisible(true);
    }
} 

...but when I run it, the frame comes up blank! Could anyone let me know what I'm doing wrong here?

Thanks a lot!

Answer

Reimeus picture Reimeus · Dec 11, 2012

You need to override the method paintComponent rather than paintMessage. Adding the @Override annotation over the method will show that paintMessage is not a standard method of JComponent. Also you may want to reduce the y-coordinate in your drawString as the text is currently not visible due to the additional decoration dimensions of the JFrame. Finally remember to call super.paintComponent to repaint the background of the component.

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2 = (Graphics2D) g;
   g2.setColor(Color.RED);
   g2.drawString("John", 5, 100);
}

See: Painting in AWT and Swing