📄 exercise14_10.java
字号:
// Exercise14_10.java: Repaint part of the viewing areaimport javax.swing.*;import java.awt.*;import java.util.*;public class Exercise14_10 extends JApplet { public void init() { getContentPane().add(new TemperatureHistogram(), BorderLayout.CENTER); } // Main method public static void main(String[] args) { // Create a frame JFrame frame = new JFrame( "Exercise14_10: Temperature Histogram"); // Create an instance of the applet Exercise14_10 applet = new Exercise14_10(); // Add the applet instance to the frame frame.getContentPane().add(applet, BorderLayout.CENTER); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Invoke init() and start() applet.init(); applet.start(); // Display the frame frame.setSize(500, 180); frame.setVisible(true); }}class TemperatureHistogram extends JPanel implements Runnable { double temperature[] = new double[24]; boolean firstTime = true; double newTemp; int current = 23; Thread thread = null; int interval, width, individualWidth, height; public TemperatureHistogram() { for (int i=0; i<temperature.length; i++) temperature[i] = 0; //Math.random()*40 + 50; thread = new Thread(this); thread.start(); } public void paintComponent(Graphics g) { //super.paintComponent(g); width = getSize().width; height = getSize().height; interval = (width-40)/24; individualWidth = (int)(((width-40)/24)*0.60); if (firstTime) { firstTime = false; int x = 30; for (int i=0; i<24; i++) { // g.drawRect(x, height-45-(int)temperature[i], individualWidth, (int)temperature[i]); g.drawString(i+"", x, height-35 ); x += interval; } FontMetrics fm = g.getFontMetrics(); String title = "Current Time: "+new Date(); g.drawLine(10, height-45, width-10, height-45); g.drawString(title, (width-fm.stringWidth(title))/2, height-20); } else { int previous = (current-1+24)%24; g.setColor(getBackground()); //Color.white); g.fillRect(interval*previous+30, height-45-(int)temperature[previous], individualWidth, (int)temperature[previous]); g.setColor(Color.black); g.drawRect(interval*previous+30, height-45-(int)temperature[previous], individualWidth, (int)temperature[previous]); g.setColor(getBackground()); g.drawRect(interval*current+30, height-45-(int)temperature[current], individualWidth, (int)temperature[current]); g.setColor(Color.red); temperature[current] = newTemp; g.fillRect(interval*current+30, height-45-(int)temperature[current], individualWidth, (int)temperature[current]); } } public void run() { //simulating temperatures of 24 hours; while (true) { try { thread.sleep(1000); // It should be 1000*60*60, but for testing 1000 is used here } catch (InterruptedException e) {} current = (current+1)%24; newTemp = (int)(Math.random()*40 + 50); repaint(); } } public Dimension getPreferredSize() { return new Dimension(300, 100); }}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -