2013-09-09 2 views
0

Я хочу добавить панель в мой класс ClockAnimation, который отображает время начала такта, время, в которое часы были остановлены, и время, прошедшее с начала до остановки. Мне бы очень хотелось, чтобы это было в формате Hour: Minute: Second. Любая помощь будет оценена по достоинству.Вычислить прошедшее время класса ClockAnimation

Мой ClockAnimation класс:

import java.awt.event.*; 
import javax.swing.*; 
import java.awt.*; 

public class ClockAnimation extends JFrame 
{ 
    //create an instance for StillClock 
    private StillClock clock = new StillClock(); 

    //create buttons 
    JButton startButton; 
    JButton stopButton; 

    //create a timer (1000 milliseconds delay) 
    Timer timer = new Timer(1000, new TimerListener()); 

    public ClockAnimation() 
    { 
     //create a panel to hold the clock 
     JPanel clockPanel = new JPanel(); 

     //add the clock to panel 
     clockPanel.add(clock); 

    //create a panel to hold start and stop buttons 
     JPanel ButtonPanel = new JPanel(); 

    //create a start button 
     startButton = new JButton("Start"); 
    //add action listener to startButton 
     startButton.addActionListener(new startListener()); 
    //create a stop button 
     stopButton = new JButton("Stop"); 
    //add action listener to stopButton 
     stopButton.addActionListener(new stopListener()); 
    //add start button to ButtonPanel 
     ButtonPanel.add(startButton); 
    //add stop button to ButtonPanel 
     ButtonPanel.add(stopButton); 

     //create elapsedPanel to hold elaped time 
     JPanel ElspsedPanel = new JPanel(); 

     //add start time to panel 
     add.(timer.start()); 
     //add stop time to panel 
     add.(timer.stop()); 
     //add the elapsed time to panel 
     ElapsedPanel.add((timer.start())-(timer.stop())); 


    //add the clockPanel and ButtonPanel to the frame 
     add(clockPanel, BorderLayout.NORTH); 
     add(ButtonPanel, BorderLayout.CENTER); 
     add(ElapsedPanel, BorderLayout.SOUTH); 
    } 

    private class startListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
     //start clock time 
     timer.start(); 
     } 
    } 

    private class stopListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
     //stop clock time 
     timer.stop(); 
     } 
    } 

    private class TimerListener implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
     //set current time and paint clock to display current time 
     clock.setCurrentTime(); 
     clock.repaint(); 
     } 
    } 

    //main method 
    public static void main(String[] args) 
    { 
    //create a JFrame instance 
    JFrame frame = new ClockAnimation(); 

    //set title of the frame 
    frame.setTitle("My Clock"); 
    //set location of the frame to center 
    frame.setLocationRelativeTo(null); 
    //set frame to close on exit 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    //set frame to visable 
    frame.setVisible(true); 
    //set components to fit in frame 
    frame.pack(); 
    } 
} 

Мой класс ClockAnimation использует мой StillClock класс:

import java.awt.event.*; 
import javax.swing.*; 
import java.awt.*; 
import java.util.*; 

public class StillClock extends JPanel 
{ 
    //create variables for StillClock 
    public int hour; 
    private int minute; 
    private int second; 

    //create a clock with current time 
    public StillClock() 
    { 
    setCurrentTime(); 
    } 

    //create a clock with specified time 
    public StillClock(int hour, int minute, int second) 
    { 
     this.hour = hour; 
     this.minute = minute; 
     this.second = second; 
    } 

    //return hour 
    public int getHour() 
    { 
    return hour; 
    } 

    //set new hour 
    public void setHour(int hour) 
    { 
     this.hour = hour; 
    repaint(); 
    } 

    //return minutes 
    public int getMinute() 
    { 
     return minute; 
    } 

    //set new minute 
    public void setMinute(int minute) 
    { 
     this.minute = minute; 
     repaint(); 
    } 

    //return seconds 
    public int getSecond() 
    { 
     return second; 
    } 

    //set new second 
    public void setSecond(int second) 
    { 
     this.second = second; 
     repaint(); 
    } 

    //draw the clock 
    protected void paintComponent(Graphics g) 
    { 
    super.paintComponent(g); 

    int clockRadius = (int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5); 
    int xCenter = getWidth()/ 2; 
    int yCenter = getHeight()/2; 

    //draw clock circle 
    g.setColor(Color.BLACK); 
    g.drawOval(xCenter - clockRadius, yCenter - clockRadius, 2 * clockRadius, 2 * clockRadius); 

    g.drawString("12", xCenter - 5, yCenter - clockRadius + 13); 
    g.drawString("9", xCenter - clockRadius + 3, yCenter + 5); 
    g.drawString("3", xCenter + clockRadius - 10, yCenter + 3); 
    g.drawString("6", xCenter - 3, yCenter + clockRadius - 3); 

    //draw seconds hand 
    int sLength = (int)(clockRadius * 0.8); 
    int xSecond = (int)(xCenter + sLength * Math.sin(second * (2 * Math.PI/ 60))); 
    int ySecond = (int)(yCenter - sLength * Math.cos(second * (2 * Math.PI/ 60))); 
    g.drawLine(xCenter, yCenter, xSecond, ySecond); 
    g.setColor(Color.red); 

    //draw minutes hand 
    int mLength = (int)(clockRadius * 0.65); 
    int xMinute = (int)(xCenter + mLength * Math.sin(minute * (2 * Math.PI/ 60))); 
    int yMinute = (int)(yCenter - mLength * Math.cos(minute * (2 * Math.PI/ 60))); 
    g.drawLine(xCenter, yCenter, xMinute, yMinute); 
    g.setColor(Color.lightGray); 

    //draw hours hand 
    int hLength = (int)(clockRadius * 0.8); 
    int xHour = (int)(xCenter + hLength * Math.sin(hour * (2 * Math.PI/ 60))); 
    int yHour = (int)(yCenter - hLength * Math.cos(hour * (2 * Math.PI/ 60))); 
    g.drawLine(xCenter, yCenter, xHour, yHour); 
    g.setColor(Color.darkGray); 
    } 

    //set current time to StillClock variables 
    public void setCurrentTime() 
    { 
    //construct calendar for current time and date 
    Calendar calendar = new GregorianCalendar(); 

    //set current time 
    this.hour = calendar.get(Calendar.HOUR_OF_DAY); 
    this.minute = calendar.get(Calendar.MINUTE); 
    this.second = calendar.get(Calendar.SECOND); 
    } 

//get dimensions of JPanel 
    public Dimension getPreferredSize() 
    { 
    return new Dimension(200, 200); 
    } 
} 

я довольно много попробовал все, что я могу думать. Мое задание, которое для этого было выполнено, было выполнено без отображения этих времен, но я думаю, было бы здорово узнать, как добавить это. Спасибо, Samantha

ответ

0

Я не эксперт, но из того, что я могу сказать, лучшим способом было бы получить прошедшее время, используя System.currentTimeMillis(), когда вы начнете и когда вы остановите таймер. Затем вы можете вычесть второе значение из первого, чтобы найти прошедшее время в миллисекундах, а затем просто делить на 1000, чтобы получить секунды.

Пример:

int startTime; 
double currentElapsedTime; 
double endElapsedTime; 

void start() 
{ 
    timer.start(); 
    startTime = System.currentTimeMillis(); 
} 

void stop() 
{ 
    timer.stop(); 
    elapsedTime = getElapsedTime(); 
} 

void getElapsedTime()  //Could be called apart from the stop() function to 
          //get the elapsed time without stopping the timer 
{        
    currentElapsedTime = (System.currentTimeMillis() - startTime)/1000; 
} 

Это только отрывок, и я знаю, что это не идеально, но это лучший способ я знаю, чтобы сделать это.

Чтобы получить часы и минуты, вы просто возьмете endElapsedTime и разделите его на 60, чтобы получить минуты, в то время как остаток будет секундами. Повторите этот процесс, чтобы получить время в часах, но остаток будет минутами вместо секунд.

String toStandardTime(double elapsedTime) 
{ 
    int hours = 0; 
    int minutes = 0; 
    int seconds = 0; 
    String formattedTime; 

    minutes = (int) t/60; 
    seconds = (int) t%60; 
    hours = (int) minutes/60; 
    minutes = (int) minutes%60; 

    formattedTime = hours + ":" + minutes + ":" + seconds; 
    return formattedTime; 
} 

Надеюсь, это помогло!

Смежные вопросы