我正在制作模拟时钟,但我遇到了一个无法解决的问题。
我有三个课:主,时钟,指针。 Main只是创建时钟并启动所有内容。 时钟管理时钟的工作原理并对其进行绘制。 指针定义指针的作用。时钟创建三个具有不同图像和速度的指针。 在指针类中,使用参数speed。
启动计时器根据速度(即它是什么指针),指针角度将增加。 时钟在绘画时获得角度。
我的问题是,当执行某个动作时,我无法获取指针对象来告诉时钟,以便可以更新和重新绘制它?怎么解决?我无法从指针创建一个新的时钟对象,因为我遇到了大量的错误。
请帮忙!
这是代码:(忽略clock中的cycle()方法)
主要
import javax.swing.JFrame;
public class Main extends JFrame {
public Main(){
add(new Clock());
setTitle("Klocka");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400,400);
setVisible(true);
setLocationRelativeTo(null);
setResizable(false);
}
public static void main(String[] args){
new Main();
}
}
时钟:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
public class Clock extends JPanel {
private Image back;
private int angle = 1;
private int a = 1;
private int b = 0;
public Pointer pPink;
public Pointer pWeird;
public Pointer pRose;
public Clock(){
pPink = new Pointer(3600,"pink.jpg");
pWeird = new Pointer(60,"weird.jpg");
pRose = new Pointer(1,"rose.jpg");
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
if (pPink.img != null){
g2d.rotate(pPink.angle*(3.1415/180));
g2d.drawImage(pPink.getImg(), 200 ,60, this);
}
if (pWeird.img != null){
g.drawImage(pWeird.getImg(), 250, 200, null);
}
if (pRose.img != null){
g.drawImage(pRose.getImg(), 300, 200, null);
}
ImageIcon i = new ImageIcon(this.getClass().getResource("wheel.png"));
back = i.getImage();
g.drawImage(back,50,50, null);
g.dispose();
cycle();
}
public void cycle(){ // a terrible try to solve the problem...
if (angle != pPink.angle){
repaint();
System.out.println(angle);
System.out.println(pPink.angle);
System.out.println("");
angle = pPink.angle;
}
}
}
指针:
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.Timer;
public class Pointer implements ActionListener {
public int angle = 0;
public int speed;
public String fileName;
public Image img;
Timer timer;
public Pointer(int speed, String fileName) {
this.speed = speed * 1000 ;
timer = new Timer(this.speed, this);
timer.start();
this.fileName = fileName;
ImageIcon ii = new ImageIcon(getClass().getResource(this.fileName));
img = ii.getImage();
}
public Image getImg(){
return img;
}
public void actionPerformed(ActionEvent e) {
angle+= 6;
System.out.println("angle increased");
}
}
答案 0 :(得分:0)
如何尝试Observer
模式。 Clock
将是观察Pointer
的观察者。 Pointer
将在执行操作时通知Clock
。
答案 1 :(得分:0)
在Pointer类中添加对时钟的引用:
. . .
private Clock clock;
public Pointer(Clock clock, int speed, String fileName) {
this.clock = clock;
. . .
然后你可以在actionPerformed方法中调用时钟上的重绘:
. . .
public void actionPerformed(ActionEvent e) {
angle += 6;
System.out.println("angle increased");
clock.repaint();
. . .
实例指针:
. . .
public Clock(){
pPink = new Pointer(this, 3600, "pink.jpg");
pWeird = new Pointer(this, 60, "weird.jpg");
pRose = new Pointer(this, 1, "rose.jpg");
. . .