home *** CD-ROM | disk | FTP | other *** search
/ Programming Languages Suite / JBuilder8.iso / Solaris / resource / jre / demo / jfc / Java2D / src / java2d / MemoryMonitor.java < prev    next >
Encoding:
Java Source  |  2002-09-06  |  11.4 KB  |  329 lines

  1. /*
  2.  * Copyright (c) 2002 Sun Microsystems, Inc. All  Rights Reserved.
  3.  * 
  4.  * Redistribution and use in source and binary forms, with or without
  5.  * modification, are permitted provided that the following conditions
  6.  * are met:
  7.  * 
  8.  * -Redistributions of source code must retain the above copyright
  9.  *  notice, this list of conditions and the following disclaimer.
  10.  * 
  11.  * -Redistribution in binary form must reproduct the above copyright
  12.  *  notice, this list of conditions and the following disclaimer in
  13.  *  the documentation and/or other materials provided with the distribution.
  14.  * 
  15.  * Neither the name of Sun Microsystems, Inc. or the names of contributors
  16.  * may be used to endorse or promote products derived from this software
  17.  * without specific prior written permission.
  18.  * 
  19.  * This software is provided "AS IS," without a warranty of any kind. ALL
  20.  * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
  21.  * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
  22.  * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
  23.  * BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
  24.  * OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
  25.  * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
  26.  * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
  27.  * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
  28.  * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
  29.  * IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
  30.  * 
  31.  * You acknowledge that Software is not designed, licensed or intended for
  32.  * use in the design, construction, operation or maintenance of any nuclear
  33.  * facility.
  34.  */
  35.  
  36. /*
  37.  * @(#)MemoryMonitor.java    1.31 02/06/13
  38.  */
  39.  
  40. package java2d;
  41.  
  42. import java.awt.*;
  43. import java.awt.event.*;
  44. import java.awt.image.BufferedImage;
  45. import java.awt.geom.Line2D;
  46. import java.awt.geom.Rectangle2D;
  47. import java.util.Date;
  48. import javax.swing.*;
  49. import javax.swing.border.EtchedBorder;
  50. import javax.swing.border.TitledBorder;
  51.  
  52.  
  53. /**
  54.  * Tracks Memory allocated & used, displayed in graph form.
  55.  */
  56. public class MemoryMonitor extends JPanel {
  57.  
  58.     static JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");
  59.     public Surface surf;
  60.     JPanel controls;
  61.     boolean doControls;
  62.     JTextField tf;
  63.  
  64.     public MemoryMonitor() {
  65.         setLayout(new BorderLayout());
  66.         setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));
  67.         add(surf = new Surface());
  68.         controls = new JPanel();
  69.         controls.setPreferredSize(new Dimension(135,80));
  70.         Font font = new Font("serif", Font.PLAIN, 10);
  71.         JLabel label = new JLabel("Sample Rate");
  72.         label.setFont(font);
  73.         label.setForeground(Color.black);
  74.         controls.add(label);
  75.         tf = new JTextField("1000");
  76.         tf.setPreferredSize(new Dimension(45,20));
  77.         controls.add(tf);
  78.         controls.add(label = new JLabel("ms"));
  79.         label.setFont(font);
  80.         label.setForeground(Color.black);
  81.         controls.add(dateStampCB);
  82.         dateStampCB.setFont(font);
  83.         addMouseListener(new MouseAdapter() {
  84.             public void mouseClicked(MouseEvent e) {
  85.                removeAll();
  86.                if ((doControls = !doControls)) {
  87.                    surf.stop();
  88.                    add(controls);
  89.                } else {
  90.                    try { 
  91.                        surf.sleepAmount = Long.parseLong(tf.getText().trim());
  92.                    } catch (Exception ex) {}
  93.                    surf.start();
  94.                    add(surf);
  95.                }
  96.                validate();
  97.                repaint();
  98.             }
  99.         });
  100.     }
  101.  
  102.  
  103.     public class Surface extends JPanel implements Runnable {
  104.  
  105.         public Thread thread;
  106.         public long sleepAmount = 1000;
  107.         private int w, h;
  108.         private BufferedImage bimg;
  109.         private Graphics2D big;
  110.         private Font font = new Font("Times New Roman", Font.PLAIN, 11);
  111.         private Runtime r = Runtime.getRuntime();
  112.         private int columnInc;
  113.         private int pts[];
  114.         private int ptNum;
  115.         private int ascent, descent;
  116.         private float freeMemory, totalMemory;
  117.         private Rectangle graphOutlineRect = new Rectangle();
  118.         private Rectangle2D mfRect = new Rectangle2D.Float();
  119.         private Rectangle2D muRect = new Rectangle2D.Float();
  120.         private Line2D graphLine = new Line2D.Float();
  121.         private Color graphColor = new Color(46, 139, 87);
  122.         private Color mfColor = new Color(0, 100, 0);
  123.         private String usedStr;
  124.       
  125.  
  126.         public Surface() {
  127.             setBackground(Color.black);
  128.             addMouseListener(new MouseAdapter() {
  129.                 public void mouseClicked(MouseEvent e) {
  130.                     if (thread == null) start(); else stop();
  131.                 }
  132.             });
  133.         }
  134.  
  135.         public Dimension getMinimumSize() {
  136.             return getPreferredSize();
  137.         }
  138.  
  139.         public Dimension getMaximumSize() {
  140.             return getPreferredSize();
  141.         }
  142.  
  143.         public Dimension getPreferredSize() {
  144.             return new Dimension(135,80);
  145.         }
  146.  
  147.             
  148.         public void paint(Graphics g) {
  149.  
  150.             if (big == null) {
  151.                 return;
  152.             }
  153.  
  154.             big.setBackground(getBackground());
  155.             big.clearRect(0,0,w,h);
  156.  
  157.             float freeMemory = (float) r.freeMemory();
  158.             float totalMemory = (float) r.totalMemory();
  159.  
  160.             // .. Draw allocated and used strings ..
  161.             big.setColor(Color.green);
  162.             big.drawString(String.valueOf((int) totalMemory/1024) + "K allocated",  4.0f, (float) ascent+0.5f);
  163.             usedStr = String.valueOf(((int) (totalMemory - freeMemory))/1024) 
  164.                 + "K used";
  165.             big.drawString(usedStr, 4, h-descent);
  166.  
  167.             // Calculate remaining size
  168.             float ssH = ascent + descent;
  169.             float remainingHeight = (float) (h - (ssH*2) - 0.5f);
  170.             float blockHeight = remainingHeight/10;
  171.             float blockWidth = 20.0f;
  172.             float remainingWidth = (float) (w - blockWidth - 10);
  173.  
  174.             // .. Memory Free ..
  175.             big.setColor(mfColor);
  176.             int MemUsage = (int) ((freeMemory / totalMemory) * 10);
  177.             int i = 0;
  178.             for ( ; i < MemUsage ; i++) { 
  179.                 mfRect.setRect(5,(float) ssH+i*blockHeight,
  180.                                 blockWidth,(float) blockHeight-1);
  181.                 big.fill(mfRect);
  182.             }
  183.  
  184.             // .. Memory Used ..
  185.             big.setColor(Color.green);
  186.             for ( ; i < 10; i++)  {
  187.                 muRect.setRect(5,(float) ssH+i*blockHeight,
  188.                                 blockWidth,(float) blockHeight-1);
  189.                 big.fill(muRect);
  190.             }
  191.  
  192.             // .. Draw History Graph ..
  193.             big.setColor(graphColor);
  194.             int graphX = 30;
  195.             int graphY = (int) ssH;
  196.             int graphW = w - graphX - 5;
  197.             int graphH = (int) remainingHeight;
  198.             graphOutlineRect.setRect(graphX, graphY, graphW, graphH);
  199.             big.draw(graphOutlineRect);
  200.  
  201.             int graphRow = graphH/10;
  202.  
  203.             // .. Draw row ..
  204.             for (int j = graphY; j <= graphH+graphY; j += graphRow) {
  205.                 graphLine.setLine(graphX,j,graphX+graphW,j);
  206.                 big.draw(graphLine);
  207.             }
  208.         
  209.             // .. Draw animated column movement ..
  210.             int graphColumn = graphW/15;
  211.  
  212.             if (columnInc == 0) {
  213.                 columnInc = graphColumn;
  214.             }
  215.  
  216.             for (int j = graphX+columnInc; j < graphW+graphX; j+=graphColumn) {
  217.                 graphLine.setLine(j,graphY,j,graphY+graphH);
  218.                 big.draw(graphLine);
  219.             }
  220.  
  221.             --columnInc;
  222.  
  223.             if (pts == null) {
  224.                 pts = new int[graphW];
  225.                 ptNum = 0;
  226.             } else if (pts.length != graphW) {
  227.                 int tmp[] = null;
  228.                 if (ptNum < graphW) {     
  229.                     tmp = new int[ptNum];
  230.                     System.arraycopy(pts, 0, tmp, 0, tmp.length);
  231.                 } else {        
  232.                     tmp = new int[graphW];
  233.                     System.arraycopy(pts, pts.length-tmp.length, tmp, 0, tmp.length);
  234.                     ptNum = tmp.length - 2;
  235.                 }
  236.                 pts = new int[graphW];
  237.                 System.arraycopy(tmp, 0, pts, 0, tmp.length);
  238.             } else {
  239.                 big.setColor(Color.yellow);
  240.                 pts[ptNum] = (int)(graphY+graphH*(freeMemory/totalMemory));
  241.                 for (int j=graphX+graphW-ptNum, k=0;k < ptNum; k++, j++) {
  242.                     if (k != 0) {
  243.                         if (pts[k] != pts[k-1]) {
  244.                             big.drawLine(j-1, pts[k-1], j, pts[k]);
  245.                         } else {
  246.                             big.fillRect(j, pts[k], 1, 1);
  247.                         }
  248.                     }
  249.                 }
  250.                 if (ptNum+2 == pts.length) {
  251.                     // throw out oldest point
  252.                     for (int j = 1;j < ptNum; j++) {
  253.                         pts[j-1] = pts[j];
  254.                     }
  255.                     --ptNum;
  256.                 } else {
  257.                     ptNum++;
  258.                 }
  259.             }
  260.             g.drawImage(bimg, 0, 0, this);
  261.         }
  262.  
  263.  
  264.         public void start() {
  265.             thread = new Thread(this);
  266.             thread.setPriority(Thread.MIN_PRIORITY);
  267.             thread.setName("MemoryMonitor");
  268.             thread.start();
  269.         }
  270.  
  271.  
  272.         public synchronized void stop() {
  273.             thread = null;
  274.             notify();
  275.         }
  276.  
  277.  
  278.         public void run() {
  279.  
  280.             Thread me = Thread.currentThread();
  281.  
  282.             while (thread == me && !isShowing() || getSize().width == 0) {
  283.                 try {
  284.                     thread.sleep(500);
  285.                 } catch (InterruptedException e) { return; }
  286.             }
  287.     
  288.             while (thread == me && isShowing()) {
  289.                 Dimension d = getSize();
  290.                 if (d.width != w || d.height != h) {
  291.                     w = d.width;
  292.                     h = d.height;
  293.                     bimg = (BufferedImage) createImage(w, h);
  294.                     big = bimg.createGraphics();
  295.                     big.setFont(font);
  296.                     FontMetrics fm = big.getFontMetrics(font);
  297.                     ascent = (int) fm.getAscent();
  298.                     descent = (int) fm.getDescent();
  299.                 }
  300.                 repaint();
  301.                 try {
  302.                     thread.sleep(sleepAmount);
  303.                 } catch (InterruptedException e) { break; }
  304.                 if (MemoryMonitor.dateStampCB.isSelected()) {
  305.                      System.out.println(new Date().toString() + " " + usedStr);
  306.                 }
  307.             }
  308.             thread = null;
  309.         }
  310.     }
  311.  
  312.  
  313.     public static void main(String s[]) {
  314.         final MemoryMonitor demo = new MemoryMonitor();
  315.         WindowListener l = new WindowAdapter() {
  316.             public void windowClosing(WindowEvent e) {System.exit(0);}
  317.             public void windowDeiconified(WindowEvent e) { demo.surf.start(); }
  318.             public void windowIconified(WindowEvent e) { demo.surf.stop(); }
  319.         };
  320.         JFrame f = new JFrame("Java2D Demo - MemoryMonitor");
  321.         f.addWindowListener(l);
  322.         f.getContentPane().add("Center", demo);
  323.         f.pack();
  324.         f.setSize(new Dimension(200,200));
  325.         f.setVisible(true);
  326.         demo.surf.start();
  327.     }
  328. }
  329.