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!
You need to override the method
paintComponentrather thanpaintMessage. Adding the@Overrideannotation over the method will show thatpaintMessageis not a standard method ofJComponent. Also you may want to reduce the y-coordinate in yourdrawStringas the text is currently not visible due to the additional decoration dimensions of theJFrame. Finally remember to callsuper.paintComponentto repaint the background of the component.See: Painting in AWT and Swing