Java Reference
In-Depth Information
we'll make the DrawingPanel implement the ActionListener interface. Its
increasingly long header will now look like this:
public class DrawingPanel extends MouseInputAdapter
implements ActionListener {
The actionPerformed method simply needs to call repaint on the main
onscreen panel:
// used for timer that repeatedly repaints screen
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
Lastly, we'll add the following lines to the DrawingPanel 's constructor to create
and start the timer:
// start a repaint timer to refresh the screen
Timer timer = new Timer(250, this);
timer.start();
Here is the complete code for the second version of the DrawingPanel class,
which includes all the components we developed:
1 // A simple interface for drawing persistent images.
2 // Final version with events.
3
4 import java.awt.*;
5 import java.awt.event.*;
6 import java.awt.image.*;
7 import javax.swing.*;
8 import javax.swing.event.*;
9
10 public class DrawingPanel extends MouseInputAdapter
11 implements ActionListener {
12 private JFrame frame; // overall window frame
13 private JPanel panel; // drawing surface
14 private JLabel statusBar; // status bar
15 private Graphics g; // drawing pen
16
17 // constructs a drawing panel of given size
18 public DrawingPanel( int width, int height) {
19 // set up the empty image onto which we will draw
20 BufferedImage image = new BufferedImage(width, height,
21 BufferedImage.TYPE_INT_ARGB);
Search WWH ::




Custom Search