有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java双时间模拟时钟不打印两个不同的时间

我把两个不同的时间传递到两个不同的物体上,时间总是一样的。关于我该做什么有什么建议吗

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) 个答案

  1. # 1 楼答案

    时间中只有静态字段,这将保证时间实例共享相同的状态。不要这样做。将这些字段设置为实例(即非静态)字段

    • 而且,您的时间复制构造函数不会,实际上完全忽略传递给它的otherClock参数
    • 你的时间课不应该有copyHrs、copyMins等。。。字段,因为它们没有任何有用的用途
    • 你的getCopy()方法有点荒谬。把所有的分、小时和秒加在一起有什么用?这个数字没有意义。该方法不应该返回一个与当前时间实例状态相同的时间实例吗