A JFrame
is a java.awt.Component
but it also has structure. We can't just paint on a JFrame
because of its special title bar (and potentially menus, toolbars, etc - later). Instead, it has a content pane, which is a java.awt.Container
covering the drawable area. This is created when a JFrame
is created. We obtain it like this:
JFrame jf = new JFrame ("Title");
Container content = jf.getContentPane ();
jf.setSize (800, 600);
But in order to override content.paint ()
we would need to subclass it. What is usually done is to subclass a Component
(or JComponent
, in Java 2D) and place that on the content pane ...
This example shows how to make a JComponent which can be drawn on and is shown in the content area of a JFrame.
import java.awt.*;
import javax.swing.*;
public class Sheet extends JComponent
{
public static void main (String [ ] args )
{
JFrame jf = new JFrame ("Sheet");
Container c = jf.getContentPane ();
c.add (new Sheet ());
jf.setSize (600, 400);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jf.setVisible (true); // Causes a call to paint () of course!
} // main
public void paint (Graphics g)
{ // Showing some of the things you can draw:
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint (RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int wd = getSize ().width, cx = wd / 2;
int ht = getSize ().height, cy = ht / 2;
Rectangle rect = new Rectangle (4, 4, wd - 8, ht - 8);
g2.setPaint (Color.YELLOW);
g2.fill (rect);
g2.setPaint (Color.BLUE);
g2.draw (rect);
g2.setFont (new Font ("Times New Roman", Font.PLAIN, 36));
g2.setPaint (new GradientPaint (wd / 4, 0, Color.RED,
wd * 3 / 4, 0, Color.GREEN, false));
g2.drawString ("First graphics example", wd / 4, ht / 2);
} // paint
} // Sheet