/Users/lyon/j4p/src/bookExamples/ch26Graphics/ClockFrame.java

1    package bookExamples.ch26Graphics; 
2     
3    import gui.run.RunButton; 
4     
5    import javax.swing.*; 
6    import java.awt.*; 
7     
8    public class ClockFrame extends JFrame { 
9        JLabel jl = new JLabel( 
10               new java.util.Date().toString()); 
11       Container container = super.getContentPane(); 
12       JPanel bcp = new JPanel(); 
13       RunButton toggleButton = new RunButton("stop/start") { 
14           public void run() { 
15               System.out.println("start/stop was clicked"); 
16               isRunning = !isRunning; 
17               System.out.println("isRunning=" + isRunning); 
18               repaint(); 
19           } 
20       }; 
21    
22       public ClockFrame() { 
23           setSize(400, 400); 
24           container.setLayout(new BorderLayout()); 
25           container.add(jl, BorderLayout.CENTER); 
26           bcp.setLayout(new FlowLayout()); 
27           bcp.add(toggleButton); 
28           container.add(bcp, BorderLayout.SOUTH); 
29           setVisible(true); 
30       } 
31    
32       public static void main(String args[]) { 
33           new ClockFrame(); 
34       } 
35    
36       private boolean isRunning = true; 
37    
38       // In order to get the toggle button to alternately select 
39       // whether the JLabel was showing the updated time 
40       // I changed the following method so that the JLabel is 
41       // repainted every time paint is called, but setText is 
42       // only called when isRunning is true. 
43       public void paint(Graphics g) { 
44           if (isRunning) 
45               jl.setText(new java.util.Date().toString()); 
46           super.paint(g); 
47           //if (isRunning) repaint(1000); 
48           repaint(); 
49       } 
50   } 
51    
52