KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java2d > MemoryMonitor


1 /*
2  * @(#)MemoryMonitor.java 1.37 06/08/29
3  *
4  * Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions are met:
8  *
9  * -Redistribution of source code must retain the above copyright notice, this
10  * list of conditions and the following disclaimer.
11  *
12  * -Redistribution in binary form must reproduce the above copyright notice,
13  * this list of conditions and the following disclaimer in the documentation
14  * and/or other materials provided with the distribution.
15  *
16  * Neither the name of Sun Microsystems, Inc. or the names of contributors may
17  * be used to endorse or promote products derived from this software without
18  * specific prior written permission.
19  *
20  * This software is provided "AS IS," without a warranty of any kind. ALL
21  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24  * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25  * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
27  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
28  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
29  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
30  * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31  *
32  * You acknowledge that this software is not designed, licensed or intended
33  * for use in the design, construction, operation or maintenance of any
34  * nuclear facility.
35  */

36
37 /*
38  * @(#)MemoryMonitor.java 1.37 06/08/29
39  */

40
41 package java2d;
42
43 import static java.awt.Color JavaDoc.*;
44 import java.awt.*;
45 import java.awt.event.*;
46 import java.awt.image.BufferedImage JavaDoc;
47 import java.awt.geom.Line2D JavaDoc;
48 import java.awt.geom.Rectangle2D JavaDoc;
49 import java.util.Date JavaDoc;
50 import javax.swing.*;
51 import javax.swing.border.EtchedBorder JavaDoc;
52 import javax.swing.border.TitledBorder JavaDoc;
53
54
55 /**
56  * Tracks Memory allocated & used, displayed in graph form.
57  */

58 public class MemoryMonitor extends JPanel {
59
60     static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
61     public Surface surf;
62     JPanel controls;
63     boolean doControls;
64     JTextField tf;
65
66     public MemoryMonitor() {
67         setLayout(new BorderLayout());
68         setBorder(new TitledBorder JavaDoc(new EtchedBorder JavaDoc(), "Memory Monitor"));
69         add(surf = new Surface());
70         controls = new JPanel();
71         controls.setPreferredSize(new Dimension(135,80));
72         Font font = new Font("serif", Font.PLAIN, 10);
73         JLabel label = new JLabel("Sample Rate");
74         label.setFont(font);
75         label.setForeground(BLACK);
76         controls.add(label);
77         tf = new JTextField("1000");
78         tf.setPreferredSize(new Dimension(45,20));
79         controls.add(tf);
80         controls.add(label = new JLabel("ms"));
81         label.setFont(font);
82         label.setForeground(BLACK);
83         controls.add(dateStampCB);
84         dateStampCB.setFont(font);
85         addMouseListener(new MouseAdapter() {
86             public void mouseClicked(MouseEvent e) {
87                removeAll();
88                if ((doControls = !doControls)) {
89                    surf.stop();
90                    add(controls);
91                } else {
92                    try {
93                        surf.sleepAmount = Long.parseLong(tf.getText().trim());
94                    } catch (Exception JavaDoc ex) {}
95                    surf.start();
96                    add(surf);
97                }
98                revalidate();
99                repaint();
100             }
101         });
102     }
103
104
105     public class Surface extends JPanel implements Runnable JavaDoc {
106
107         public Thread JavaDoc thread;
108         public long sleepAmount = 1000;
109         private int w, h;
110         private BufferedImage JavaDoc bimg;
111         private Graphics2D big;
112         private Font font = new Font("Times New Roman", Font.PLAIN, 11);
113         private Runtime JavaDoc r = Runtime.getRuntime();
114         private int columnInc;
115         private int pts[];
116         private int ptNum;
117         private int ascent, descent;
118         private float freeMemory, totalMemory;
119         private Rectangle graphOutlineRect = new Rectangle();
120         private Rectangle2D JavaDoc mfRect = new Rectangle2D.Float JavaDoc();
121         private Rectangle2D JavaDoc muRect = new Rectangle2D.Float JavaDoc();
122         private Line2D JavaDoc graphLine = new Line2D.Float JavaDoc();
123         private Color JavaDoc graphColor = new Color JavaDoc(46, 139, 87);
124         private Color JavaDoc mfColor = new Color JavaDoc(0, 100, 0);
125         private String JavaDoc usedStr;
126       
127
128         public Surface() {
129             setBackground(BLACK);
130             addMouseListener(new MouseAdapter() {
131                 public void mouseClicked(MouseEvent e) {
132                     if (thread == null) start(); else stop();
133                 }
134             });
135         }
136
137         public Dimension getMinimumSize() {
138             return getPreferredSize();
139         }
140
141         public Dimension getMaximumSize() {
142             return getPreferredSize();
143         }
144
145         public Dimension getPreferredSize() {
146             return new Dimension(135,80);
147         }
148
149             
150         public void paint(Graphics g) {
151
152             if (big == null) {
153                 return;
154             }
155
156             big.setBackground(getBackground());
157             big.clearRect(0,0,w,h);
158
159             float freeMemory = (float) r.freeMemory();
160             float totalMemory = (float) r.totalMemory();
161
162             // .. Draw allocated and used strings ..
163
big.setColor(GREEN);
164             big.drawString(String.valueOf((int) totalMemory/1024) + "K allocated", 4.0f, (float) ascent+0.5f);
165             usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024)
166                 + "K used";
167             big.drawString(usedStr, 4, h-descent);
168
169             // Calculate remaining size
170
float ssH = ascent + descent;
171             float remainingHeight = (float) (h - (ssH*2) - 0.5f);
172             float blockHeight = remainingHeight/10;
173             float blockWidth = 20.0f;
174             float remainingWidth = (float) (w - blockWidth - 10);
175
176             // .. Memory Free ..
177
big.setColor(mfColor);
178             int MemUsage = (int) ((freeMemory / totalMemory) * 10);
179             int i = 0;
180             for ( ; i < MemUsage ; i++) {
181                 mfRect.setRect(5,(float) ssH+i*blockHeight,
182                                 blockWidth,(float) blockHeight-1);
183                 big.fill(mfRect);
184             }
185
186             // .. Memory Used ..
187
big.setColor(GREEN);
188             for ( ; i < 10; i++) {
189                 muRect.setRect(5,(float) ssH+i*blockHeight,
190                                 blockWidth,(float) blockHeight-1);
191                 big.fill(muRect);
192             }
193
194             // .. Draw History Graph ..
195
big.setColor(graphColor);
196             int graphX = 30;
197             int graphY = (int) ssH;
198             int graphW = w - graphX - 5;
199             int graphH = (int) remainingHeight;
200             graphOutlineRect.setRect(graphX, graphY, graphW, graphH);
201             big.draw(graphOutlineRect);
202
203             int graphRow = graphH/10;
204
205             // .. Draw row ..
206
for (int j = graphY; j <= graphH+graphY; j += graphRow) {
207                 graphLine.setLine(graphX,j,graphX+graphW,j);
208                 big.draw(graphLine);
209             }
210         
211             // .. Draw animated column movement ..
212
int graphColumn = graphW/15;
213
214             if (columnInc == 0) {
215                 columnInc = graphColumn;
216             }
217
218             for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {
219                 graphLine.setLine(j,graphY,j,graphY+graphH);
220                 big.draw(graphLine);
221             }
222
223             --columnInc;
224
225             if (pts == null) {
226                 pts = new int[graphW];
227                 ptNum = 0;
228             } else if (pts.length != graphW) {
229                 int tmp[] = null;
230                 if (ptNum < graphW) {
231                     tmp = new int[ptNum];
232                     System.arraycopy(pts, 0, tmp, 0, tmp.length);
233                 } else {
234                     tmp = new int[graphW];
235                     System.arraycopy(pts, pts.length-tmp.length, tmp, 0, tmp.length);
236                     ptNum = tmp.length - 2;
237                 }
238                 pts = new int[graphW];
239                 System.arraycopy(tmp, 0, pts, 0, tmp.length);
240             } else {
241                 big.setColor(YELLOW);
242                 pts[ptNum] = (int)(graphY+graphH*(freeMemory/totalMemory));
243                 for (int j=graphX+graphW-ptNum, k=0;k < ptNum; k++, j++) {
244                     if (k != 0) {
245                         if (pts[k] != pts[k-1]) {
246                             big.drawLine(j-1, pts[k-1], j, pts[k]);
247                         } else {
248                             big.fillRect(j, pts[k], 1, 1);
249                         }
250                     }
251                 }
252                 if (ptNum+2 == pts.length) {
253                     // throw out oldest point
254
for (int j = 1;j < ptNum; j++) {
255                         pts[j-1] = pts[j];
256                     }
257                     --ptNum;
258                 } else {
259                     ptNum++;
260                 }
261             }
262             g.drawImage(bimg, 0, 0, this);
263         }
264
265
266         public void start() {
267             thread = new Thread JavaDoc(this);
268             thread.setPriority(Thread.MIN_PRIORITY);
269             thread.setName("MemoryMonitor");
270             thread.start();
271         }
272
273
274         public synchronized void stop() {
275             thread = null;
276             notify();
277         }
278
279
280         public void run() {
281
282             Thread JavaDoc me = Thread.currentThread();
283
284             while (thread == me && !isShowing() || getSize().width == 0) {
285                 try {
286                     thread.sleep(500);
287                 } catch (InterruptedException JavaDoc e) { return; }
288             }
289     
290             while (thread == me && isShowing()) {
291                 Dimension d = getSize();
292                 if (d.width != w || d.height != h) {
293                     w = d.width;
294                     h = d.height;
295                     bimg = (BufferedImage JavaDoc) createImage(w, h);
296                     big = bimg.createGraphics();
297                     big.setFont(font);
298                     FontMetrics fm = big.getFontMetrics(font);
299                     ascent = (int) fm.getAscent();
300                     descent = (int) fm.getDescent();
301                 }
302                 repaint();
303                 try {
304                     thread.sleep(sleepAmount);
305                 } catch (InterruptedException JavaDoc e) { break; }
306                 if (MemoryMonitor.dateStampCB.isSelected()) {
307                      System.out.println(new Date JavaDoc().toString() + " " + usedStr);
308                 }
309             }
310             thread = null;
311         }
312     }
313
314
315     public static void main(String JavaDoc s[]) {
316         final MemoryMonitor demo = new MemoryMonitor();
317         WindowListener l = new WindowAdapter() {
318             public void windowClosing(WindowEvent e) {System.exit(0);}
319             public void windowDeiconified(WindowEvent e) { demo.surf.start(); }
320             public void windowIconified(WindowEvent e) { demo.surf.stop(); }
321         };
322         JFrame f = new JFrame("Java2D Demo - MemoryMonitor");
323         f.addWindowListener(l);
324         f.getContentPane().add("Center", demo);
325         f.pack();
326         f.setSize(new Dimension(200,200));
327         f.setVisible(true);
328         demo.surf.start();
329     }
330 }
331
Popular Tags