Displaying Text
Home ] Up ] JFrame Internal Structure ] Graphics Context ] [ Displaying Text ] Text & Fonts ] Mixing Fonts ] Finding & Displaying Fonts ]

 

 

The paintComponent()method

In order to display text in a content pane, you have to:

  1. Create a class that extends JPanel
  2. Implement paintComponent(Graphics g) in that class;  this is where all the drawing of text occurs

    • The first thing this method should do is call super.paintComponent(g) -- if you don't, you will most likely find that strange things happen.
    • The rest of the code in the method should cause graphic elements to be displayed -- in this case, we'll be displaying text.
  3. Finally:
    • Create an instance of this class and add it to the JFrame's content pane.
Note:  In addition to the paintComponent(Graphics g) method, there is also a paint(Graphics g) method.  Don't get confused between the two methods:
  • If you're programming in Swing, use paintComponent  
  • If you're programming in AWT, use paint

Here's an example:

package swingExamples;

import java.awt.Container;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

class TextDisplayPanel extends JPanel
{
  public void paintComponent(Graphics g)
  {
    // Don't forget to do this!
    super.paintComponent(g);
    // Display the text in the panel
    g.drawString("Hello from a Java Swing application!", 50, 80);
  }
}

class TextDisplayFrame extends JFrame
{
  public TextDisplayFrame()
  {
    setTitle("Text Display Frame");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    // Find the JFrame's content pane
    Container contentPane = getContentPane();
    // Add the TextDisplayPanel to the content pane
    contentPane.add( new TextDisplayPanel() );
  }
}

public class TextDisplay
{
  public static void main(String[] args)
  {
    TextDisplayFrame frame = new TextDisplayFrame();
    frame.setVisible(true);
  }
}

Here's the result:

 

This page was last modified on 02 October, 2007