Java Reference
In-Depth Information
6. To avoid compile errors, the CirclePanel class (lines 38-53) now is also defined as
an inner class in ControlCircle , since another CirclePanel class is already
defined in Listing 16.2.
L ISTING 16.3 ControlCircle.java
1 import javax.swing.*;
2 import java.awt.*;
3 import java.awt.event.*;
4
5 public class ControlCircle extends JFrame {
6
VideoNote
Listener and its registration
private JButton jbtEnlarge = new JButton( "Enlarge" );
7
private JButton jbtShrink = new JButton( "Shrink" );
8
private CirclePanel canvas = new CirclePanel();
9
10 public ControlCircle() {
11 JPanel panel = new JPanel(); // Use the panel to group buttons
12 panel.add(jbtEnlarge);
13 panel.add(jbtShrink);
14
15
this .add(canvas, BorderLayout.CENTER); // Add canvas to center
16
this .add(panel, BorderLayout.SOUTH); // Add buttons to the frame
17
18
19 }
20
21 /** Main method */
22 public static void main(String[] args) {
23 JFrame frame = new ControlCircle();
24 frame.setTitle( "ControlCircle" );
25 frame.setLocationRelativeTo( null ); // Center the frame
26 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
27 frame.setSize( 200 , 200 );
28 frame.setVisible( true );
29 }
30
31
jbtEnlarge.addActionListener( new EnlargeListener());
create/register listener
class EnlargeListener implements ActionListener {
listener class
// Inner class
32 @Override
33
34
35
36
37
38
public void actionPerformed(ActionEvent e) {
canvas.enlarge();
}
}
class CirclePanel extends JPanel {
// Inner class
CirclePanel class
39
private int radius = 5 ; // Default circle radius
40
41
/** Enlarge the circle */
42
43
44
45
46
47 @Override
48 protected void paintComponent(Graphics g) {
49 super .paintComponent(g);
50 g.drawOval(getWidth() / 2 - radius, getHeight() / 2 - radius,
51
public void enlarge() {
enlarge method
radius++;
repaint();
}
2 * radius, 2 * radius);
52 }
53 }
54 }
 
Search WWH ::




Custom Search