Academic Java    Java Tutorial  >  Swing  >  drawing on a JFrame

drawing on a JFrame Example

Java drawing on a JFrame EXAMPLE output This JFrame example shows how to draw directly onto the surface of a JFrame. It does this by overriding its paint() method.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// JFrame drawing example
import java.awt.*;
import javax.swing.*;

class JFrameDrawingExample extends JFrame {

   FontMetrics fm;
   String s = "Leon Wildboar";

   public JFrameDrawingExample() {
      super("My Name");
      Font font = new Font("Jokerman", Font.ITALIC, 36);
      setFont(font);
      fm = getFontMetrics(font);
      setSize(fm.stringWidth(s)+30, fm.getHeight()+60);

      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setVisible(true);
   }

   public void paint(Graphics g) {

      Insets ins = getInsets();
      int w = getSize().width-ins.left-ins.right;
      int h = getSize().height-ins.top-ins.bottom;

      int centerX = w/2 + ins.left;
      int centerY = h/2 + ins.top;

      g.setColor(Color.red);
      g.fillRect(ins.left, ins.top, w, h);

      g.setColor(Color.yellow);
      g.drawString(
         s, 
         centerX-fm.stringWidth(s)/2, 
         centerY + (fm.getAscent()-fm.getDescent())/2
      );
   }

   static public void main(String[] args) {
      new JFrameDrawingExample();
   }

}

12 A font is constructed with parameters: font family/face name, style, and size (the point size of the font).
But as described in Java documentation this is not always the one hoped for.

14-15 Each font object has a FontMetrics object associated with it.
This has methods such as stringWidth() and stringHeight() for retrieving information about the size of the string with the given font.
We use it here to set the size of the frame, with some extra space added.

34-38 The second and third parameters of drawString() are the coordinates of the baseline of the first character of the string.
We use the font metrics object and its methods to center the string in the frame.

* JFrame Examples