Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package myclock;
- import java.awt.Color;
- import java.awt.Graphics;
- import java.awt.Graphics2D;
- import javax.swing.JComponent;
- import javax.swing.JFrame;
- public class Display {
- private String title;
- private int size;
- private static JFrame frame;
- // Current clock time
- private static int hours = 0, minutes = 0;
- public Display(String title,int size) {
- this.title=title;
- this.size=size;
- createDisplay();
- }
- public void createDisplay() {
- // Create a JFrame where we will put our clock
- frame = new JFrame(title);
- // Set up the frame
- frame.setSize(size, size);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setResizable(false);
- // Add a Component object inside the frame. This Component object
- // is responsible for drawing shapes and it does so by overriding
- // the paint method of the Component class. See PaintComponent
- // definition below
- frame.add(new PaintComponent());
- frame.setVisible(true);
- }
- public void setTime(int hours, int minutes) {
- this.hours = hours;
- this.minutes = minutes;
- // Let the system know we have to redraw. This will call
- // PaintComponent.paint() which will call drawClock()
- // which will use the updated hours and minutes values to redraw
- // the clock
- frame.repaint();
- }
- /*
- * drawClock
- *
- * Helper function to draw the clock and its hands
- *
- * Arguments:
- * g2D: Graphics2D object to use when drawing
- */
- private static void drawClock(Graphics2D g2D) {
- // This is a test line to show you this is working. Still need to draw
- // a clock instead
- g2D.drawString(String.valueOf(hours) + ":" + String.valueOf(minutes),
- 100, 100);
- // TODO: Draw clock face
- // e.g g2D.drawOval(0, 0, 300, 300);
- // TODO: Draw clock hands
- // Use the hours and minutes variable to determine
- // what the current time is.
- }
- static class PaintComponent extends JComponent {
- // This callback function is called every time the system feels the
- // need to paint the component (window resized, previously obscured
- // area now visible etc.). It helps to think of it this way: the
- // function clears up the Component and draws whatever is written below
- @Override
- public void paint(Graphics g) {
- // g is a Graphics type but Graphics doesn't support drawing
- // shapes so we cast it to Graphics2D
- Graphics2D g2d = (Graphics2D) g;
- g2d.setColor(Color.BLACK);
- drawClock(g2d);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement