Java Swing How to - Draw text with graphics object on JFrame








Question

We would like to know how to draw text with graphics object on JFrame.

Answer

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
//from   w w  w . ja  v a 2  s . c o  m
import javax.swing.JComponent;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JFrame jf = new JFrame();
    Container cp = jf.getContentPane();
    MyCanvas tl = new MyCanvas();
    cp.add(tl);
    jf.setSize(300, 200);
    jf.setVisible(true);
  }
}

class MyCanvas extends JComponent {

  @Override
  public void paintComponent(Graphics g) {
    if (g instanceof Graphics2D) {
      Graphics2D g2 = (Graphics2D) g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
          RenderingHints.VALUE_ANTIALIAS_ON);

      g2.drawString("This is gona be awesome", 70, 20);
    }
  }
}