Path: blob/master/src/demo/share/jfc/J2Ddemo/java2d/MemoryMonitor.java
41155 views
/*1*2* Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved.3*4* Redistribution and use in source and binary forms, with or without5* modification, are permitted provided that the following conditions6* are met:7*8* - Redistributions of source code must retain the above copyright9* notice, this list of conditions and the following disclaimer.10*11* - Redistributions in binary form must reproduce the above copyright12* notice, this list of conditions and the following disclaimer in the13* documentation and/or other materials provided with the distribution.14*15* - Neither the name of Oracle nor the names of its16* contributors may be used to endorse or promote products derived17* from this software without specific prior written permission.18*19* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS20* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,21* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR22* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR23* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,24* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,25* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR26* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF27* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING28* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS29* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.30*/31package java2d;323334import static java.awt.Color.BLACK;35import static java.awt.Color.GREEN;36import static java.awt.Color.YELLOW;37import java.awt.BorderLayout;38import java.awt.Color;39import java.awt.Dimension;40import java.awt.Font;41import java.awt.FontMetrics;42import java.awt.Graphics;43import java.awt.Graphics2D;44import java.awt.Rectangle;45import java.awt.event.MouseAdapter;46import java.awt.event.MouseEvent;47import java.awt.event.WindowAdapter;48import java.awt.event.WindowEvent;49import java.awt.event.WindowListener;50import java.awt.geom.Line2D;51import java.awt.geom.Rectangle2D;52import java.awt.image.BufferedImage;53import java.util.Date;54import javax.swing.JCheckBox;55import javax.swing.JFrame;56import javax.swing.JLabel;57import javax.swing.JPanel;58import javax.swing.JTextField;59import javax.swing.border.EtchedBorder;60import javax.swing.border.TitledBorder;616263/**64* Tracks Memory allocated & used, displayed in graph form.65*/66@SuppressWarnings("serial")67public class MemoryMonitor extends JPanel {6869private final JCheckBox dateStampCB = new JCheckBox("Output Date Stamp");70public Surface surf;71JPanel controls;72boolean doControls;73JTextField tf;7475public MemoryMonitor() {76setLayout(new BorderLayout());77setBorder(new TitledBorder(new EtchedBorder(), "Memory Monitor"));78add(surf = new Surface());79controls = new JPanel();80controls.setPreferredSize(new Dimension(135, 80));81Font font = new Font(Font.SERIF, Font.PLAIN, 10);82JLabel label = new JLabel("Sample Rate");83label.setFont(font);84label.setForeground(BLACK);85controls.add(label);86tf = new JTextField("1000");87tf.setPreferredSize(new Dimension(45, 20));88controls.add(tf);89controls.add(label = new JLabel("ms"));90label.setFont(font);91label.setForeground(BLACK);92controls.add(dateStampCB);93dateStampCB.setFont(font);94addMouseListener(new MouseAdapter() {9596@Override97public void mouseClicked(MouseEvent e) {98removeAll();99if ((doControls = !doControls)) {100surf.stop();101add(controls);102} else {103try {104surf.sleepAmount = Long.parseLong(tf.getText().trim());105} catch (Exception ex) {106}107surf.start();108add(surf);109}110revalidate();111repaint();112}113});114}115116117public class Surface extends JPanel implements Runnable {118119public Thread thread;120public long sleepAmount = 1000;121private int w, h;122private BufferedImage bimg;123private Graphics2D big;124private Font font = new Font(Font.SERIF, Font.PLAIN, 11);125private Runtime r = Runtime.getRuntime();126private int columnInc;127private int[] pts;128private int ptNum;129private int ascent, descent;130private Rectangle graphOutlineRect = new Rectangle();131private Rectangle2D mfRect = new Rectangle2D.Float();132private Rectangle2D muRect = new Rectangle2D.Float();133private Line2D graphLine = new Line2D.Float();134private Color graphColor = new Color(46, 139, 87);135private Color mfColor = new Color(0, 100, 0);136private String usedStr;137138public Surface() {139setBackground(BLACK);140addMouseListener(new MouseAdapter() {141142@Override143public void mouseClicked(MouseEvent e) {144if (thread == null) {145start();146} else {147stop();148}149}150});151}152153@Override154public Dimension getMinimumSize() {155return getPreferredSize();156}157158@Override159public Dimension getMaximumSize() {160return getPreferredSize();161}162163@Override164public Dimension getPreferredSize() {165return new Dimension(135, 80);166}167168@Override169public void paint(Graphics g) {170171if (big == null) {172return;173}174175big.setBackground(getBackground());176big.clearRect(0, 0, w, h);177178float freeMemory = r.freeMemory();179float totalMemory = r.totalMemory();180181// .. Draw allocated and used strings ..182big.setColor(GREEN);183big.drawString(String.valueOf((int) totalMemory / 1024)184+ "K allocated", 4.0f, ascent + 0.5f);185usedStr = String.valueOf(((int) (totalMemory - freeMemory)) / 1024)186+ "K used";187big.drawString(usedStr, 4, h - descent);188189// Calculate remaining size190float ssH = ascent + descent;191float remainingHeight = (h - (ssH * 2) - 0.5f);192float blockHeight = remainingHeight / 10;193float blockWidth = 20.0f;194195// .. Memory Free ..196big.setColor(mfColor);197int MemUsage = (int) ((freeMemory / totalMemory) * 10);198int i = 0;199for (; i < MemUsage; i++) {200mfRect.setRect(5, ssH + i * blockHeight,201blockWidth, blockHeight - 1);202big.fill(mfRect);203}204205// .. Memory Used ..206big.setColor(GREEN);207for (; i < 10; i++) {208muRect.setRect(5, ssH + i * blockHeight,209blockWidth, blockHeight - 1);210big.fill(muRect);211}212213// .. Draw History Graph ..214big.setColor(graphColor);215int graphX = 30;216int graphY = (int) ssH;217int graphW = w - graphX - 5;218int graphH = (int) remainingHeight;219graphOutlineRect.setRect(graphX, graphY, graphW, graphH);220big.draw(graphOutlineRect);221222int graphRow = graphH / 10;223224// .. Draw row ..225for (int j = graphY; j <= graphH + graphY; j += graphRow) {226graphLine.setLine(graphX, j, graphX + graphW, j);227big.draw(graphLine);228}229230// .. Draw animated column movement ..231int graphColumn = graphW / 15;232233if (columnInc == 0) {234columnInc = graphColumn;235}236237for (int j = graphX + columnInc; j < graphW + graphX; j +=238graphColumn) {239graphLine.setLine(j, graphY, j, graphY + graphH);240big.draw(graphLine);241}242243--columnInc;244245if (pts == null) {246pts = new int[graphW];247ptNum = 0;248} else if (pts.length != graphW) {249int[] tmp = null;250if (ptNum < graphW) {251tmp = new int[ptNum];252System.arraycopy(pts, 0, tmp, 0, tmp.length);253} else {254tmp = new int[graphW];255System.arraycopy(pts, pts.length - tmp.length, tmp, 0,256tmp.length);257ptNum = tmp.length - 2;258}259pts = new int[graphW];260System.arraycopy(tmp, 0, pts, 0, tmp.length);261} else {262big.setColor(YELLOW);263pts[ptNum] =264(int) (graphY + graphH * (freeMemory / totalMemory));265for (int j = graphX + graphW - ptNum, k = 0; k < ptNum; k++, j++) {266if (k != 0) {267if (pts[k] != pts[k - 1]) {268big.drawLine(j - 1, pts[k - 1], j, pts[k]);269} else {270big.fillRect(j, pts[k], 1, 1);271}272}273}274if (ptNum + 2 == pts.length) {275// throw out oldest point276for (int j = 1; j < ptNum; j++) {277pts[j - 1] = pts[j];278}279--ptNum;280} else {281ptNum++;282}283}284g.drawImage(bimg, 0, 0, this);285}286287public void start() {288thread = new Thread(this);289thread.setPriority(Thread.MIN_PRIORITY);290thread.setName("MemoryMonitor");291thread.start();292}293294public synchronized void stop() {295thread = null;296notify();297}298299@Override300@SuppressWarnings("SleepWhileHoldingLock")301public void run() {302303Thread me = Thread.currentThread();304305while (thread == me && !isShowing() || getSize().width == 0) {306try {307Thread.sleep(500);308} catch (InterruptedException e) {309return;310}311}312313while (thread == me && isShowing()) {314Dimension d = getSize();315if (d.width != w || d.height != h) {316w = d.width;317h = d.height;318bimg = (BufferedImage) createImage(w, h);319big = bimg.createGraphics();320big.setFont(font);321FontMetrics fm = big.getFontMetrics(font);322ascent = fm.getAscent();323descent = fm.getDescent();324}325repaint();326try {327Thread.sleep(sleepAmount);328} catch (InterruptedException e) {329break;330}331if (dateStampCB.isSelected()) {332System.out.println(new Date().toString() + " " + usedStr);333}334}335thread = null;336}337}338339public static void main(String[] s) {340final MemoryMonitor demo = new MemoryMonitor();341WindowListener l = new WindowAdapter() {342343@Override344public void windowClosing(WindowEvent e) {345System.exit(0);346}347348@Override349public void windowDeiconified(WindowEvent e) {350demo.surf.start();351}352353@Override354public void windowIconified(WindowEvent e) {355demo.surf.stop();356}357};358JFrame f = new JFrame("J2D Demo - MemoryMonitor");359f.addWindowListener(l);360f.getContentPane().add("Center", demo);361f.pack();362f.setSize(new Dimension(200, 200));363f.setVisible(true);364demo.surf.start();365}366}367368369