Question

In JAVA, please: Write a program that draws a clock face with a time that the...

In JAVA, please:

Write a program that draws a clock face with a time that the user enters in two text fields (one for the hours, one for the minutes).
Hint: You need to determine the angles of the hour hand and the minute hand. The angle of the minute hand is easy; the minute hand travels 360 degrees in 60 minutes.
The angle of the hour hand is harder; it travels 360 degrees in 12 × 60 minutes.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Please find the code below::

DrawClockUtil.java

package graphichal2;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
class DrawClockWithUserInput extends JPanel
{
   private int minute = 10;
   private int hour = 12;
   DrawClockWithUserInput(int hour,int min){
       this.hour = hour;
       this.minute = min;
   }

   int xcenter = 175, ycenter = 175;
   private void drawStructure(Graphics g){
       g.setColor(Color.black);
       g.fillOval(xcenter - 150, ycenter - 150, 300, 300);
       g.setColor(Color.green);
       g.drawString("9", xcenter - 145, ycenter +0);
       g.drawString("3", xcenter + 135, ycenter + 0);
       g.drawString("12", xcenter - 10, ycenter - 130);
       g.drawString("6", xcenter - 10, ycenter + 145);
   }
   public void paint(Graphics g) {
       int xhour, yhour, xminute, yminute;
       drawStructure(g);
       xminute = (int) (Math.cos(minute * 3.14f / 30 - 3.14f / 2) * 100 + xcenter);
       yminute = (int) (Math.sin(minute * 3.14f / 30 - 3.14f / 2) * 100 + ycenter);
       xhour = (int) (Math.cos((hour * 30 + minute / 2) * 3.14f / 180 - 3.14f / 2) * 80 + xcenter);
       yhour = (int) (Math.sin((hour * 30 + minute / 2) * 3.14f / 180 - 3.14f / 2) * 80 + ycenter);

       g.setColor(Color.red);
       g.drawLine(xcenter, ycenter - 1, xminute, yminute);
       g.setColor(Color.green);
       g.drawLine(xcenter - 1, ycenter, xhour, yhour);
   }
}


public class DrawClockUtil{
   static DrawClockWithUserInput clock;
   public static void main(String args[]) {
       final JFrame window = new JFrame();
       window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       window.setBounds(0, 0, 600, 600);
       window.setLayout(null);


       final JTextField input1=new JTextField("");
       input1.setBounds(100, 10, 50,50);
       window.add(input1);

       final JTextField input2=new JTextField("");
       input2.setBounds(150, 10, 50,50);
       window.add(input2);


       JButton button1=new JButton("Draw Clock");
       button1.setBounds(200, 10, 120,50);
       window.add(button1);


       button1.addActionListener(new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent arg0) {
               if(clock!=null)
               window.remove(clock);
               try{
                   clock = new DrawClockWithUserInput(Integer.parseInt(input1.getText())
                           ,Integer.parseInt(input2.getText()));
                   clock.setBounds(100, 200, 500,500);
                   window.add(clock);    
                   window.repaint();
               }catch(Exception e){
                   JOptionPane.showMessageDialog(null, "Invalid time entered!!!");
               }
           }
       });

       window.setVisible(true);
   }
}

Add a comment
Answer #2

Sure! Below is a Java program that draws a simple clock face using the Swing library and takes user inputs for the hours and minutes to set the time for the clock.

javaCopy codeimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class ClockFaceApp extends JFrame {    private JTextField hourTextField, minuteTextField;    private ClockPanel clockPanel;    public ClockFaceApp() {
        setTitle("Clock Face");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());        // Create text fields for user input
        hourTextField = new JTextField(5);
        minuteTextField = new JTextField(5);        // Create a button to update the clock face
        JButton updateButton = new JButton("Update");
        updateButton.addActionListener(new ActionListener() {            @Override
            public void actionPerformed(ActionEvent e) {
                updateClock();
            }
        });        // Create a panel to hold the clock face
        clockPanel = new ClockPanel();        // Add components to the frame
        JPanel inputPanel = new JPanel();
        inputPanel.add(new JLabel("Hours: "));
        inputPanel.add(hourTextField);
        inputPanel.add(new JLabel("Minutes: "));
        inputPanel.add(minuteTextField);
        inputPanel.add(updateButton);

        add(inputPanel, BorderLayout.NORTH);
        add(clockPanel, BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }    private void updateClock() {        try {            int hours = Integer.parseInt(hourTextField.getText());            int minutes = Integer.parseInt(minuteTextField.getText());
            clockPanel.setClockTime(hours, minutes);
            clockPanel.repaint();
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this, "Invalid input. Please enter numeric values for hours and minutes.");
        }
    }    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {            public void run() {                new ClockFaceApp();
            }
        });
    }
}class ClockPanel extends JPanel {    private int hours;    private int minutes;    public void setClockTime(int hours, int minutes) {        this.hours = hours % 12; // Convert hours to 12-hour format
        this.minutes = minutes;
    }    @Override
    protected void paintComponent(Graphics g) {        super.paintComponent(g);        int centerX = getWidth() / 2;        int centerY = getHeight() / 2;        int clockRadius = Math.min(centerX, centerY) - 10;        // Draw the clock face
        g.setColor(Color.BLACK);
        g.drawOval(centerX - clockRadius, centerY - clockRadius, clockRadius * 2, clockRadius * 2);        // Draw clock hands
        drawHand(g, centerX, centerY, clockRadius * 0.6, Math.toRadians((hours + minutes / 60.0) * 30 - 90)); // 30 degrees per hour
        drawHand(g, centerX, centerY, clockRadius * 0.8, Math.toRadians(minutes * 6 - 90)); // 6 degrees per minute
    }    private void drawHand(Graphics g, int x, int y, double length, double angle) {        int handX = (int) (x + length * Math.cos(angle));        int handY = (int) (y + length * Math.sin(angle));
        g.drawLine(x, y, handX, handY);
    }
}

This program creates a simple GUI application using Java Swing. It allows the user to enter the hours and minutes in separate text fields and then updates the clock face accordingly. The clock face consists of a circle representing the clock and two hands for the hour and minute. The hour hand travels 30 degrees per hour (360 degrees in 12 hours), and the minute hand travels 6 degrees per minute (360 degrees in 60 minutes). The program uses trigonometric functions to calculate the position of the hands based on the given time.


answered by: Mayre Yıldırım
Add a comment
Answer #3

Sure, here's a Java program that draws a clock face based on the time entered by the user in two text fields for hours and minutes:

javaCopy codeimport javax.swing.*;import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;public class ClockFace extends JPanel {    private int hours;    private int minutes;    public ClockFace() {
        setPreferredSize(new Dimension(300, 300));
    }    public void setHours(int hours) {        this.hours = hours;
    }    public void setMinutes(int minutes) {        this.minutes = minutes;
    }    @Override
    protected void paintComponent(Graphics g) {        super.paintComponent(g);
        drawClockFace(g);
    }    private void drawClockFace(Graphics g) {        int centerX = getWidth() / 2;        int centerY = getHeight() / 2;        int radius = 100;        // Draw clock outline
        g.setColor(Color.BLACK);
        g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);        // Draw hour hand
        int hourHandLength = 40;        double hourAngle = Math.toRadians(360.0 * (hours % 12 + minutes / 60.0) / 12.0);        int hourHandX = centerX + (int) (hourHandLength * Math.cos(hourAngle));        int hourHandY = centerY - (int) (hourHandLength * Math.sin(hourAngle));
        g.drawLine(centerX, centerY, hourHandX, hourHandY);        // Draw minute hand
        int minuteHandLength = 60;        double minuteAngle = Math.toRadians(360.0 * minutes / 60.0);        int minuteHandX = centerX + (int) (minuteHandLength * Math.cos(minuteAngle));        int minuteHandY = centerY - (int) (minuteHandLength * Math.sin(minuteAngle));
        g.drawLine(centerX, centerY, minuteHandX, minuteHandY);
    }    public static void main(String[] args) {        JFrame frame = new JFrame("Clock Face");        ClockFace clockFace = new ClockFace();        JLabel hourLabel = new JLabel("Hours:");        JTextField hourTextField = new JTextField(2);        JLabel minuteLabel = new JLabel("Minutes:");        JTextField minuteTextField = new JTextField(2);        JButton drawButton = new JButton("Draw");
        drawButton.addActionListener(new ActionListener() {            @Override
            public void actionPerformed(ActionEvent e) {                int hours = Integer.parseInt(hourTextField.getText());                int minutes = Integer.parseInt(minuteTextField.getText());
                clockFace.setHours(hours);
                clockFace.setMinutes(minutes);
                clockFace.repaint();
            }
        });        JPanel inputPanel = new JPanel();
        inputPanel.add(hourLabel);
        inputPanel.add(hourTextField);
        inputPanel.add(minuteLabel);
        inputPanel.add(minuteTextField);
        inputPanel.add(drawButton);

        frame.setLayout(new BorderLayout());
        frame.add(clockFace, BorderLayout.CENTER);
        frame.add(inputPanel, BorderLayout.SOUTH);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}

This program creates a simple GUI application using Swing that allows the user to enter the hours and minutes in text fields and click the "Draw" button to display the clock face with the corresponding hour and minute hands. The hour and minute hands' angles are calculated based on the user input and drawn on the clock face accordingly.

answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
In JAVA, please: Write a program that draws a clock face with a time that the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with turtle graphics assignment in python 3, please! Write a program named Lastname_firstname_clock.py to display a clock face with hands showing the current time. The radius of the clock...

    I need help with turtle graphics assignment in python 3, please! Write a program named Lastname_firstname_clock.py to display a clock face with hands showing the current time. The radius of the clock face (the distance from the center to the hour markers) is 150. The hour hand has length 100, and the minute hand has a length of 120 You may design the clock in one of three ways: using the square cursor shape (hint: stamp)) for the hour markers...

  • HELP IN JAVA: WHILE LOOP: Write a program that asks the user to enter a number...

    HELP IN JAVA: WHILE LOOP: Write a program that asks the user to enter a number of seconds. This number should be less than or equal to 32767 because that is the largest number pep8 can handle. Your program should then output the number of hours, minutes, and seconds on the planet of Crypton, where there are 64 seconds in a minute and 32 minutes in an hour.

  • JAVA PROGRAM. Write a program to implement a class Clock whose getHours and getMinutes methods return the current time a...

    JAVA PROGRAM. Write a program to implement a class Clock whose getHours and getMinutes methods return the current time at your location. Also include a getTime method that returns a string with the hours and minutes by calling the getHours and getMinutes methods. Provide a subclass WorldClock whose constructor accepts a time offset. For example, if you livein California, a new WorldCLock(3) should show the time in NewYork, three time zones ahead. Include an Alarm feature in the Clock class....

  • need help with this JAVA lab, the starting code for the lab is below. directions: The...

    need help with this JAVA lab, the starting code for the lab is below. directions: The Clock class has fields to store the hours, minutes and meridian (a.m. or p.m.) of the clock. This class also has a method that compares two Clock instances and returns the one that is set to earlier in the day. The blahblahblah class has a method to get the hours, minutes and meridian from the user. Then a main method in that class creates...

  • a. Suppose we want to develop software for an alarm clock. The clock shows the time...

    a. Suppose we want to develop software for an alarm clock. The clock shows the time of a day. Using buttons, the user can set the hours and minutes fields individually, and choose between 12 and 24-hour display. It is possible to set one or two alarms. When an alarm is triggered, it will sound some noise. The user can turn it off, or choose to 'snooze'. If the user does not respond at all, the alarm will turn off...

  • [Java] We have learned the class Clock, which was designed to implement the time of day...

    [Java] We have learned the class Clock, which was designed to implement the time of day in a program. Certain application in addition to hours, minutes, and seconds might require you to store the time zone. Please do the following: Derive the class ExtClock from the class Clock by adding a data member to store the time zone. Add necessary methods and constructors to make the class functional. Also write the definitions of the methods and constructors. Write a test...

  • Need help with this java code supposed to be a military time clock, but I need...

    Need help with this java code supposed to be a military time clock, but I need help creating the driver to test and run the clock. I also need help making the clock dynamic. public class Clock { private int hr; //store hours private int min; //store minutes private int sec; //store seconds public Clock () { setTime (0, 0, 0); } public Clock (int hours, intminutes, int seconds) { setTime (hours, minutes, seconds); } public void setTime (int hours,int...

  • Programming & user functions in MATLAB: Please provide the files & results in your submittal. Prepare...

    Programming & user functions in MATLAB: Please provide the files & results in your submittal. Prepare a MATLAB program that finds the angle between the hour and minute hands on a circular clock. The program asks the user to enter the time in hours and minutes, as well as whether the time is AM or PM (although the algorithm will not use AM or PM). The program should report the angle in degrees, measured to two decimal places. The largest...

  • C++ Question 6 (10pt): Convert seconds Write a program that takes a number of seconds as...

    C++ Question 6 (10pt): Convert seconds Write a program that takes a number of seconds as user input (as an integer) and converts it to hours, minutes, and seconds as shown below. You should convert the amount of time in such a way that maximizes the whole numbers of hours and minutes. Expected output 1 (bold is user input) Enter a number of seconds: 60 0 hour(s) 1 minute(s) 0 second(s) Expected output 2 (bold is user input) Enter a...

  • Write a GUI-based Java application that implements the "Math Game" shown below. The program asks the...

    Write a GUI-based Java application that implements the "Math Game" shown below. The program asks the user to enter the answer of multiplying two one-digit random integers.  If the user enters a correct answer, a message will be displayed at the bottom of the frame, and the text field will be cleared.  If the user enters a wrong answer, a message will be displayed at the bottom of the frame asking for another answer.  If the user...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT