01: package snow.utils.gui;
02:
03: import javax.swing.*;
04: import java.awt.event.MouseAdapter;
05: import java.awt.event.*;
06: import java.awt.*;
07: import java.text.*;
08:
09: /** Displays the jvm memory usage, automatically updated.
10: */
11: public class MemoryInfoPanel extends JPanel {
12: final JLabel jvmMemoryLabel;
13: final JLabel appMemoryLabel;
14: final DecimalFormat nf = new DecimalFormat("#");
15:
16: public MemoryInfoPanel() {
17: super ();
18: setLayout(new FlowLayout(FlowLayout.RIGHT, 10, 2));
19: setOpaque(false);
20: jvmMemoryLabel = new JLabel();
21: appMemoryLabel = new JLabel();
22: add(jvmMemoryLabel);
23: add(appMemoryLabel);
24:
25: addMouseListener(new MouseAdapter() {
26: @Override
27: public void mousePressed(MouseEvent me) {
28: if (me.isPopupTrigger()) {
29: showPopup(me);
30: return;
31: }
32: }
33:
34: @Override
35: public void mouseReleased(MouseEvent me) {
36: if (me.isPopupTrigger()) {
37: showPopup(me);
38: return;
39: }
40: }
41: });
42:
43: start();
44: }
45:
46: private void showPopup(final MouseEvent me) {
47: final JPopupMenu popup = new JPopupMenu(
48: "Memory info panel context menu");
49: JMenuItem gcCall = new JMenuItem("Perform Garbage Collection");
50: popup.add(gcCall);
51: gcCall.addActionListener(new ActionListener() {
52: public void actionPerformed(ActionEvent ae) {
53: System.gc();
54: }
55: });
56:
57: popup.show(this , me.getX(), me.getY());
58: }
59:
60: private void start() {
61: final Thread memoryDisplayUpdater = new Thread() {
62: public void run() {
63: while (true) {
64: try {
65: Thread.sleep(4000);
66: } catch (Exception ignore) {
67: }
68:
69: EventQueue.invokeLater(new Runnable() {
70: public void run() {
71: final double jvmMemory = Runtime
72: .getRuntime().totalMemory() / 1.0e6;
73: final double appMemory = jvmMemory
74: - Runtime.getRuntime().freeMemory()
75: / 1.0e6;
76: //jvmMemoryLabel.setText("JVM " + nf.format(jvmMemory) + " MB");
77: appMemoryLabel.setText("App "
78: + nf.format(appMemory) + " MB ");
79:
80: setToolTipText("JVM "
81: + nf.format(jvmMemory)
82: + " MB App "
83: + nf.format(appMemory) + " MB");
84: }
85: });
86: }
87: }
88: };
89: memoryDisplayUpdater.setDaemon(true);
90: memoryDisplayUpdater.setName("MemoryInfoPanel");
91: memoryDisplayUpdater.start();
92: }
93:
94: }
|