created (Applets): 03/07/1998; revised: 07/15/2002, 08/18/2003, 11/02/2003, 02/11/2006, 12/03/2010, (No Applets): 06/27/2016
This chapter explains how to use Java to draw pictures.
You can create a window (a JFrame
), put a sheet of graph paper in it (a JPanel
), and draw on it as if using a pen and a ruler
(drawLine()
) or using a template with ovals and rectangles.
You can change the color of the pen and the color of the paper.
In this chapter there is no user interaction. In later chapters, on GUI, the user interacts with the running program.
Graphics programing in Java is done using Swing. The AWT also contains some older components which are no longer used. Swing integrates smoothly with the Java Foundation Classes. The Java Foundation Classes provide many classes needed for modern software development.
JFrame
classJFrame
class:
setSize()
setVisible()
setDefaultCloseOperation()
add()
pack()
JPanel
classJPanel
class:
setBackground( )
setPreferredSize()
paintComponent()
getWidth()
getHeight()
Graphics
classGraphics
class:
setColor()
drawLine()
drawOval()
and fillOval()
drawRect()
and fillRect()
In computer programming, what is a window?