Java Reference
In-Depth Information
L
ISTING
16.2
ControlCircleWithoutEventHandling.java
1
import
javax.swing.*;
2
import
java.awt.*;
3
4
public class
ControlCircleWithoutEventHandling
extends
JFrame {
5
private
JButton jbtEnlarge =
new
JButton(
"Enlarge"
);
buttons
6
private
JButton jbtShrink =
new
JButton(
"Shrink"
);
7
8
9
public
ControlCircleWithoutEventHandling() {
10 JPanel panel =
new
JPanel();
// Use the panel to group buttons
11 panel.add(jbtEnlarge);
12 panel.add(jbtShrink);
13
14
private
CirclePanel canvas =
new
CirclePanel();
circle canvas
this
.add(canvas, BorderLayout.CENTER);
// Add canvas to center
15
this
.add(panel, BorderLayout.SOUTH);
// Add buttons to the frame
16 }
17
18
/** Main method */
19
public static void
main(String[] args) {
20 JFrame frame =
new
ControlCircleWithoutEventHandling();
21 frame.setTitle(
"ControlCircleWithoutEventHandling"
);
22 frame.setLocationRelativeTo(
null
);
// Center the frame
23 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
24 frame.setSize(
200
,
200
);
25 frame.setVisible(
true
);
26 }
27 }
28
29
class
CirclePanel
extends
JPanel {
30
CirclePanel
class
private int
radius =
5
;
// Default circle radius
31
32 @Override
/** Repaint the circle */
33
protected void
paintComponent(Graphics g) {
paint the circle
34
super
.paintComponent(g);
35
36
37 }
38 }
g.drawOval(getWidth() /
2
- radius, getHeight() /
2
- radius,
2
* radius,
2
* radius);
How do you use the buttons to enlarge or shrink the circle? When the
Enlarge
button is clicked,
you want the circle to be repainted with a larger radius. How can you accomplish this? You can
expand the program in Listing 16.2 into Listing 16.3 with the following features:
second version
1. Define a listener class named
EnlargeListener
that implements
ActionListener
(lines 31-36).
2. Create a listener and register it with
jbtEnlarge
(line 18).
3. Add a method named
enlarge()
in
CirclePanel
to increase the radius, then repaint
the panel (lines 42-45).
4. Implement the
actionPerformed
method in
EnlargeListener
to invoke
canvas.enlarge()
(line 34).
5. To make the reference variable
canvas
accessible from the
actionPerformed
method, define
EnlargeListener
as an inner class of the
ControlCircle
class
(lines 31-36). (
Inner classes
are defined inside another class. We will introduce inner
classes in the next section.)
inner class