Creating a Drawing Surface

Before you can start using the Graphics class, you need something to draw on.

One component that's suitable for this purpose is JPanel in the javax.swing package. This class represents panels in a graphical user interface that can be empty or contain other components.

The following example creates a frame and a panel, and adds the panel to the frame window:

JFrame main = new JFrame("Main Menu");
JPanel pane = new JPanel();
main.getContentPane().add(pane);

The frame's getContentPane() method returns an object representing the portion of the frame that can contain other components. That object's add() method is called to add the panel to the frame.

Like many other user interface components in Java, JPanel objects have ...

Get Sams Teach Yourself Java 2 in 21 Days, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.