// File $CISC370HOME/example-progs/threads/animation/ThermCanvas.java import java.util.*; // for Interface Observer import java.awt.*; import javax.swing.*; public class ThermoCanvas extends JPanel implements Observer { Thermometer currT; // Variable for thermometer being observed public ThermoCanvas( Thermometer T ) { currT = T; T.addObserver( this ); // Register ThermoCanvas as observer of T } public void update(Observable o, Object x)// From interface Observer { System.out.println("Entering ThermoCanvas.update(Observable,Object)"); repaint(); } public void paintComponent(Graphics g) { super.paintComponent( g ); System.out.println("Entering ThermoCanvas method paint()"); Dimension d = getSize(); // Get size of canvas int thermometerH = 3*d.height/4; // Calculate thermometer display height int thermometerW = 10; // and display width int xOrigin = (d.width - thermometerW)/2; // Center thermometer int yOrigin = (d.height - thermometerH)/2; // on canvas // Draw empty tube g.drawRect(xOrigin, yOrigin, thermometerW, thermometerH); // Mark tube with temperature readings g.setFont(new Font("Helvetica", Font.PLAIN, 8)); FontMetrics f = g.getFontMetrics(); int fH = f.getHeight(); int minTemp = currT.getMinTemp(); int maxTemp = currT.getMaxTemp(); int temp = currT.getTemp(); g.drawLine(xOrigin + 14, yOrigin, xOrigin + 19, yOrigin); // Max temp g.drawString(maxTemp + " F", xOrigin + 23, yOrigin + fH/2); g.drawLine(xOrigin + 14, yOrigin + thermometerH/2, // Mid temp xOrigin + 19, yOrigin + thermometerH/2); g.drawString(((maxTemp - minTemp)/2) + " F", xOrigin + 23, yOrigin + (thermometerH + fH)/2); g.drawLine(xOrigin + 14, yOrigin + thermometerH, // Min temp xOrigin + 19, yOrigin + thermometerH); g.drawString(minTemp + " F", xOrigin + 23, yOrigin + thermometerH + fH/2); // Calculate mercury height int mercuryH = thermometerH*(temp - minTemp)/(maxTemp - minTemp); // Fill tube w red mercury Color prevColor = g.getColor(); // Save current color g.setColor(Color.red); g.fillRect(xOrigin+1, yOrigin + thermometerH - mercuryH, thermometerW-1, mercuryH); // Draw bulb at bottom filled w red mercury g.fillOval(xOrigin - thermometerW/2+1, yOrigin + thermometerH+1, 2*thermometerW-2, 2*thermometerW-2); g.setColor(prevColor); // Restore previous color g.drawOval(xOrigin - thermometerW/2, yOrigin + thermometerH, 2*thermometerW, 2*thermometerW); // Write title g.setFont(new Font("Helvetica", Font.BOLD, 10)); f = g.getFontMetrics(); String title = currT.getTitle(); g.drawString(title, (d.width - f.stringWidth(title))/2, yOrigin + thermometerH + 2*(thermometerW + fH)); } public Dimension getMinimumSize() { System.out.println("Entering ThermoCanvas method minimumSize()"); return new Dimension(100,200); } public Dimension getPreferredSize() { System.out.println("Entering ThermoCanvas method preferredSize()"); return new Dimension(200,400); } }