2015-10-06 2 views
-1

Я передаю два разных раза на два разных объекта, и время всегда одно и то же. Любые предложения относительно того, что я должен делать?Двойные аналоговые часы не печатают два разных раза

public class TwoTimeClock extends JFrame { 

    Clock clockFace; 
    Clock clockFacetwo; 

    public static void main(String[] args) { 
     JFrame windo = new TwoTimeClock(); 
     windo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     windo.setVisible(true); 
    } 
    private final Clock clockFaceTwo; 

    /** 
    * empty constructor. initializes instance variables, draws the clocks, 
    * and starts them 
    */ 
    public TwoTimeClock() { 
     Container content = this.getContentPane(); 
     content.setLayout(new BorderLayout()); 

     Time time1 = new Time(); 
     Time time2 = new Time(); 



     clockFace = new Clock(time1); 
     clockFaceTwo = new Clock(time2); 

     content.add(clockFace, BorderLayout.WEST); //BorderLayout.WEST and BorderLayout.EAST decide the clocks lie in the left or right of box 
     //hint if you add another clockFace to the content object above, then the canvas will grow in size 
     content.add(clockFaceTwo, BorderLayout.EAST); 

     this.setTitle("Baltimore           New Delhi"); 
     this.pack(); 
     clockFace.start(); 

     time2.setHrsOffset(9); 
     time2.setMinsOffset(30); 

     clockFaceTwo.start(); 

    } 
} 

Время;

private static final int spacing = 10; 
private static final float threePi = (float) (3.0 * Math.PI); 
// Angles for the trigonometric functions are measured in radians. 
// The following in the number of radians per sec or min. 
private static final float radPerSecMin = (float) (Math.PI/30.0); 
private int size; // height and width of clock face 
private int centerX; // x coord of middle of clock 
private int centerY; // y coord of middle of clock 
private BufferedImage clockImage; 
private javax.swing.Timer t; 


/** 
* //>>>>>>>>>>>>>>>>> You should modify this constructor to take an object of Time class as parameter 
* Constructor. Takes an object of the Time class that it will use for showing the time 
* @param 
*/ 

public Clock(Time t1) { 
    this.time = t1; 
    this.setPreferredSize(new Dimension(300, 300)); 
    this.setBackground(Color.white); 
    this.setForeground(Color.black); 
    t = new javax.swing.Timer(1000, 
      new ActionListener() { 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        update(); 
       } 
      }); 
} 
/** 
* Replace the default update so that the plain background doesn't get drawn. 
*/ 

public void update() { 
    this.repaint(); 
} 

public void start() { 
    t.start(); // start the timer 
} 

public void stop() { 
    t.stop(); // stop the timer 
} 

@Override 
public void paintComponent(Graphics g) { 
    super.paintComponent(g); // paint background, borders 
    Graphics2D g2 = (Graphics2D) g; 
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
      RenderingHints.VALUE_ANTIALIAS_ON); 

    // The panel may have been resized, get current dimensions 
    int w = getWidth(); 
    int h = getHeight(); 
    size = ((w < h) ? w : h) - 2 * spacing; 
    size -= 50; //reducing size to make space for text below clock face 

    centerX = size/2 + spacing; 
    centerY = size/2 + spacing; 

    // Create the clock face background image if this is the first time, 
    // or if the size of the panel has changed 
    if (clockImage == null 
      || clockImage.getWidth() != w 
      || clockImage.getHeight() != h) { 
     clockImage = (BufferedImage) (this.createImage(w, h)); 

    // now get a graphics context from this image 
     Graphics2D gc = clockImage.createGraphics(); 
     gc.setRenderingHint(RenderingHints.KEY_ANTIALIASING, 
       RenderingHints.VALUE_ANTIALIAS_ON); 
     drawClockFace(gc); 
    } 



    time.update(); 
    time.updateOffSet(); 
    //>>>>>>>>>>>>>>>>>>>>>>> 

    // Draw the clock face from the precomputed image 
    g2.drawImage(clockImage, null, 0, 0); 

    // Draw the clock hands 
    drawClockHands(g); 


    //Print Clock 
    g2.drawString(Time.toStandard(), 90, h-15); 
    g2.drawString(Time.toMilitary(), 90, h-30); 

} 

/** 
* The hour, minute, and second hand 
* @param g 
*/ 
private void drawClockHands(Graphics g) { 
    int secondRadius = size/2; 
    int minuteRadius = secondRadius * 3/4; 
    int hourRadius = secondRadius/2; 

    // second hand 
    float fseconds = time.getSecs() + (float) time.getMillis()/ 1000; 
    float secondAngle = threePi - (radPerSecMin * fseconds); 
    drawRadius(g, centerX, centerY, secondAngle, 0, secondRadius); 

    // minute hand clock 1 
    float fminutes = (float) (time.getMins() + fseconds/60.0); 
    float minuteAngle = threePi - (radPerSecMin * fminutes); 
    drawRadius(g, centerX, centerY, minuteAngle, 0, minuteRadius); 


    // hour hand clock 1 
    float fhours = (float) (time.getHrs() + fminutes/60.0); 
    float hourAngle = threePi - (5 * radPerSecMin * fhours); 
    drawRadius(g, centerX, centerY, hourAngle, 0, hourRadius); 

} 


private void drawClockFace(Graphics g) { 
    // clock face 
    g.setColor(Color.lightGray); 
    g.fillOval(spacing, spacing, size, size); 
    g.setColor(Color.black); 
    g.drawOval(spacing, spacing, size, size); 

    // tic marks 
    for (int sec = 0; sec < 60; sec++) { 
     int ticStart; 
     if (sec % 5 == 0) { 
      ticStart = size/2 - 10; 
     } else { 
      ticStart = size/2 - 5; 
     } 
     drawRadius(g, centerX, centerY, radPerSecMin * sec, ticStart, size/2); 
    } 
} 

private void drawRadius(Graphics g, int x, int y, double angle, 
     int minRadius, int maxRadius) { 
    float sine = (float) Math.sin(angle); 
    float cosine = (float) Math.cos(angle); 
    int dxmin = (int) (minRadius * sine); 
    int dymin = (int) (minRadius * cosine); 
    int dxmax = (int) (maxRadius * sine); 
    int dymax = (int) (maxRadius * cosine); 
    g.drawLine(x + dxmin, y + dymin, x + dxmax, y + dymax); 
} 

} 

public class Time { 

    private static int hrs = 00; 
    private static int mins = 00; 
    private static int secs = 00; 
    private static int millis = 00; 
    static int copyHrs; 
    static int copyMins; 
    static int copySecs; 
    static int hrsOffset; 
    static int minsOffset = 30; 

    //Empty Constructor 
    public Time() { 
     Calendar t1 = Calendar.getInstance(); 
     hrs = t1.get(Calendar.HOUR); 
     mins = t1.get(Calendar.MINUTE); 
     secs = t1.get(Calendar.SECOND); 
     millis = t1.get(Calendar.MILLISECOND); 
    } 

    //Alternate Constructor 
    public Time(int hours, int minutes, int seconds, int millisec) { 
     hrs = hours; 
     mins = minutes; 
     secs = seconds; 
     millis = millisec; 
    } 

    //Copy Constructor 
    public Time(Time otherClock) { 
     copyHrs = hrs; 
     copyMins = mins; 
     copySecs = secs; 
     millis = millis; 
    } 

    public int getHrs() { 
     return hrs; 
    } 

    public void setHrs(int hrs) { 
     this.hrs = hrs; 
    } 

    public int getMins() { 
     return mins; 
    } 

    public void setMins(int mins) { 
     this.mins = mins; 
    } 

    public int getSecs() { 
     return secs; 
    } 

    public void setSecs(int secs) { 
     this.secs = secs; 
    } 

    public int getMillis() { 
     return millis; 
    } 

    public void setMillis(int millis) { 
     this.millis = millis; 
    } 

    public static int getHrsOffset() { 
     return hrsOffset; 
    } 

    public void setHrsOffset(int hrsOffset) { 
     this.hrsOffset = hrsOffset; 
    } 

    public void printOffset(Time clock, int hrsOffset, int minsOffset) { 
     hrs = Math.abs(clock.hrs + hrsOffset); 
     mins = Math.abs(clock.mins + minsOffset); 
     secs = clock.secs; 
     if (hrs < 12) { 
      System.out.printf("%02d:%02d:%02d AM%n", hrs, mins, secs); 
     } else if (hrs == 24) { 
      System.out.printf("12:%02d:%02d AM%n", mins, secs); 
     } else if (hrs == 12) { 
      System.out.printf("12:%02d:%02d PM%n", mins, secs); 
     } else { 
      System.out.printf("%02d:%02d:%02d PM%n", hrs - 12, mins, secs); 
     } 
    } 

    public static int getMinsOffset() { 
     return minsOffset; 
    } 

    public void setMinsOffset(int minsOffset) { 
     this.minsOffset = minsOffset; 
    } 

    public static void printMilitary() { 
     hrs = hrs % 24; 
     System.out.printf("%02d:%02d:%02d %n", hrs, mins, secs); 
    } 

    public static void printStandard() { 
     hrs = hrs % 24; 
     if (hrs < 12) { 
      System.out.printf("%02d:%02d:%02d AM%n", hrs, mins, secs); 
     } else if (hrs == 24) { 
      System.out.printf("12:%02d:%02d AM%n", mins, secs); 
     } else if (hrs == 12) { 
      System.out.printf("12:%02d:%02d PM%n", mins, secs); 
     } else { 
      System.out.printf("%02d:%02d:%02d PM%n", hrs - 12, mins, secs); 
     } 
    } 

    @Override 
    public String toString() { 
     return hrs + ":" + mins + ":" + secs; 
    } 

    public boolean equals(Time otherClock) { 
     if (hrs == otherClock.hrs && mins == otherClock.mins && secs == otherClock.secs) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public static int getCopy() { 
     copyHrs = Time.hrs; 
     copyMins = Time.mins; 
     copySecs = Time.secs; 
     return copyHrs + copyMins + copySecs; 
    } 

    public static void advanceSecs() { 
     secs++; 
     if (secs > 59) { 
      mins++; 
      secs = 00; 
     } 
     if (mins > 59) { 
      hrs++; 
      secs = 00; 
      mins = 00; 
     } 
    } 

    public boolean lessThan(Time otherClock) { 
     if ((hrs < otherClock.hrs) && (mins < otherClock.mins) && (secs < otherClock.secs)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public boolean notEquals(Time otherClock) { 
     if ((hrs == otherClock.hrs) && (mins == otherClock.mins) && (secs == otherClock.secs)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public boolean lessOrEquals(Time otherClock) { 
     if ((hrs <= otherClock.hrs) && (mins <= otherClock.mins) && (secs <= otherClock.secs)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public boolean greaterThan(Time otherClock) { 
     if ((hrs > otherClock.hrs) && (mins > otherClock.mins) && (secs > otherClock.secs)) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

    public static String toMilitary() { 
     hrs = hrs%24; 
     String str = String.format("%02d:%02d:%02d", hrs, mins, secs); 
     return str; 
    } 

    public static String toStandard() { 
     String str = String.format("%02d:%02d:%02d PM", hrs, mins, secs); 

     if (hrs > 12) { 
      hrs = hrs - 12; 
      str = String.format("%02d:%02d:%02d AM", hrs, mins, secs); 
        } else if (hrs == 12) { 
      str = String.format("%02d:%02d:%02d AM", hrs, mins, secs); 
      } 
     return str; 
    } 

    public void update() { 
     Calendar t1 = Calendar.getInstance(); 
     hrs = t1.get(Calendar.HOUR);  
     mins = t1.get(Calendar.MINUTE); 
     secs = t1.get(Calendar.SECOND); 
     millis = t1.get(Calendar.MILLISECOND); 

    } 
    public void updateOffSet() { 
     Calendar t1 = Calendar.getInstance(); 
     hrs = t1.get(Calendar.HOUR) + hrsOffset;  
     mins = t1.get(Calendar.MINUTE) + minsOffset; 
     secs = t1.get(Calendar.SECOND); 
     millis = t1.get(Calendar.MILLISECOND); 

    } 
} 
+1

Не обновляйте состояние 'Time' из метода' paintComponent', этот метод можно вызвать по разным причинам, а не обновлять его в Swing 'Timer'. Есть целый API с миллионами человеческих часов, введенных в них для управления датой/временем, такими как «Календарь», JodaTime и Java API Time 8, я настоятельно рекомендую вам использовать их – MadProgrammer

ответ

3

У тебя нет ничего, кроме статических полей во время, и это будет гарантировать, что экземпляры времени будет все один и то же состояние. Не делай этого. Сделайте эти поля экземпляром (т. Е. Нестатические) поля.

  • Кроме того, ваш конструктор Time copy не выполняет и фактически полностью игнорирует параметр otherClock, который переходит в него.
  • В вашем классе времени не должно быть полей copyHrs, copyMins и т. Д., Поскольку они не служат никакой полезной цели.
  • Ваш метод getCopy() является немного абсурдным. Какое использование добавляет все минуты, часы и секунды вместе? Число не имеет смысла. Должен ли этот метод возвращать экземпляр Time, один с тем же состоянием, что и текущий экземпляр Time?
+1

И используйте подходящий API времени, например JodaTime или Java 8 Time API и не обновлять 'Time' в методе' paintComponent' ... Довольно много, если бы имелось правило, которое можно было бы сломать здесь, я думаю, что они завершили его разбиение, приятно :) – MadProgrammer

+0

@MadProgrammer: True, true! Я даже не получил отладки части GUI еще, поскольку я только что пытался исправить часть модели. –

+1

Вы должны были сказать, я мог бы дать вам свой код, прежде чем я его удалю: P. OP никогда не присваивает 't1' чему-либо в классе' Clock', но в любом случае нет поля для его назначения, они также не запускают '' Timer''. Я в основном преодолел функциональность класса «Время» и обернул ее вокруг «LocalTime», WAY проще: P – MadProgrammer