Question

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!

Was it helpful?

Solution

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

OTHER TIPS

You need to add this line after public void paintMessage(Graphics g){ :

super.paint(g);

This tells Java to use the superclass (JComponent) to paint the message.

You will also need to call your method paintComponents() rather than paintMessage()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top