1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.diyefi.openlogviewer;
24
25 import java.awt.Dimension;
26 import java.awt.FlowLayout;
27 import java.awt.event.ActionEvent;
28 import java.awt.event.ActionListener;
29 import java.text.DecimalFormat;
30 import java.text.DecimalFormatSymbols;
31 import java.text.NumberFormat;
32 import java.util.ResourceBundle;
33
34 import javax.swing.JLabel;
35 import javax.swing.JPanel;
36 import javax.swing.Timer;
37
38 public class FramesPerSecondPanel extends JPanel implements ActionListener {
39 private static final long serialVersionUID = 1L;
40 private static final int PREFERRED_WIDTH = 80;
41 private static final int PPREFERRED_HEIGHT = 16;
42 private static final int TIMER_RATE = 250;
43 private static final double MILLISECONDS_PER_SECOND = 1000d;
44
45 private static final char ZERO = '0';
46 private static final char DS = DecimalFormatSymbols.getInstance().getDecimalSeparator();
47 private static final char TS = DecimalFormatSymbols.getInstance().getGroupingSeparator();
48 private static final String FORMAT = "#" + TS + "##0" + DS + ZERO;
49
50 private static final DecimalFormat DF = (DecimalFormat) NumberFormat.getNumberInstance();
51 static {
52 DF.applyLocalizedPattern(FORMAT);
53 }
54
55 private static long frameCount;
56 private static long thePast;
57 private static long currentTime;
58 private static long previousCount;
59
60 private final String framesPerSecond;
61
62 private final JLabel output;
63 private final Timer sampleTimer;
64
65 private Double fps;
66
67 public FramesPerSecondPanel(final ResourceBundle labels) {
68 setName("fpsPanel");
69 setPreferredSize(new Dimension(PREFERRED_WIDTH, PPREFERRED_HEIGHT));
70 setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
71
72 framesPerSecond = labels.getString(Text.FRAMES_PER_SECOND);
73 final String defaultFpsLabel = framesPerSecond + ZERO + DS + ZERO;
74 output = new JLabel(defaultFpsLabel);
75 output.setVerticalTextPosition(JLabel.CENTER);
76 output.setHorizontalTextPosition(JLabel.CENTER);
77 this.add(output);
78
79
80 sampleTimer = new Timer(TIMER_RATE, this);
81 sampleTimer.setInitialDelay(0);
82 sampleTimer.start();
83 currentTime = System.currentTimeMillis();
84 thePast = currentTime;
85 }
86
87 public static void increaseFrameCount() {
88 currentTime = System.currentTimeMillis();
89 frameCount++;
90 }
91
92 @Override
93 public final void actionPerformed(final ActionEvent e) {
94 if (e.getSource().equals(sampleTimer)) {
95 final long sampleWindow = currentTime - thePast;
96 final long sampleCount = frameCount - previousCount;
97 if (sampleWindow == 0L) {
98 fps = 0d;
99 } else {
100 fps = ((double) sampleCount / (double) sampleWindow) * MILLISECONDS_PER_SECOND;
101 }
102 output.setText(framesPerSecond + DF.format(fps));
103 previousCount = frameCount;
104 thePast = currentTime;
105 }
106 }
107
108 }