Trying to use drawString method to print a name

16,327

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

Share:
16,327
John Dawson
Author by

John Dawson

Updated on June 04, 2022

Comments

  • John Dawson
    John Dawson almost 2 years

    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!

  • imulsion
    imulsion over 11 years
    no problem. just remember to upvote good answers and accept best answer (hint, hint)