所以我有这个任务,我必须同时移动两个对象。我知道我应该使用线程类,但我不知道该怎么做。我的项目有两个文件。第一个有main方法并实现fan对象。这是:
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
public class DrawArcs extends JFrame {
public DrawArcs() {
setTitle("DrawArcs");
add(new ArcsPanel());
}
/** Main method */
public static void main(String[] args) {
DrawArcs frame = new DrawArcs();
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setVisible(true);
frame.add(new StillClock());
}
}
class ArcsPanel extends JPanel {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int)(Math.min(getWidth(), getHeight()) * 0.4);
int x = xCenter - radius;
int y = yCenter - radius;
g.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
}
}
我的第二个文件包括时钟类的实现。
public class StillClock extends JPanel {
private int hour;
private int minute;
private int second;
public StillClock() {
setCurrentTime();
}
public StillClock(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
////there are setters and getters here
.
.
.
////
@Override /** Draw the clock */
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Initialize clock parameters
int clockRadius =
(int)(Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
// Draw circle
g.setColor(Color.black);
g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
2 * clockRadius, 2 * clockRadius);
g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
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 second 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.setColor(Color.red);
g.drawLine(xCenter, yCenter, xSecond, ySecond);
// Draw minute 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.setColor(Color.blue);
g.drawLine(xCenter, yCenter, xMinute, yMinute);
// Draw hour hand
int hLength = (int)(clockRadius * 0.5);
int xHour = (int)(xCenter + hLength *
Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
int yHour = (int)(yCenter - hLength *
Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
g.setColor(Color.green);
g.drawLine(xCenter, yCenter, xHour, yHour);
}
public void setCurrentTime() {
// Construct a calendar for the current date and time
Calendar calendar = new GregorianCalendar();
// Set current hour, minute and second
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
所以我的问题是如何让风扇和时钟同时旋转?
以下是您运行代码enter image description here
的样子答案 0 :(得分:1)
所以,你实际上问了两个问题:
2D图形中的旋转相对容易,有许多可能的选项。我将使用AffineTransform
作为个人偏好。
我们需要向ArcsPanel
添加一些内容,我们需要一个代表当前旋转角度的angle
和一个代表运动量的delta
在每个动画传递...
public static class ArcsPanel extends JPanel {
protected static final float DELTA = 1.0f;
private float angle = 0;
有了这些信息,我们只需修改paintComponent
方法即可支持angle
属性并应用AffineTransform
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));
int x = xCenter - radius;
int y = yCenter - radius;
g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
g2d.dispose();
}
尽管您可能会想到,但您不需要更多线程,实际上只需要一个。这一个线程将通知您要更新的所有对象,他们应该更新其可动画状态。这个线程并不关心他们如何做到这一点,它只会驱动这个过程。同样,您的对象并不关心引擎是如何工作的,只是它会定期通知它们。
现在,Swing既是单线程的,也不是线程安全的。在处理线程时,这会引发许多问题。您无法在事件调度线程的上下文中运行长时间运行或阻塞操作,也不应该从EDT外部更新UI的状态。
为简单起见,Swing Timer
是一个完美的选择,因为它等待EDT,但会触发它在EDT中的更新。
首先,我们需要一些方法让引擎告诉其他对象他们应该自己更新。当然,您可以简单地保持对其他组件的直接引用,但这既增加了对象之间的耦合,也限制了引擎的可重用性。
相反,我们定义了一个简单的界面......
public interface Animatable {
public void updateAnimatedState();
}
所有想要通知的对象都将实现此interface
并可以向引擎注册
public class Engine {
private List<Animatable> animatables;
private Timer timer;
public Engine() {
animatables = new ArrayList<>(4);
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (Animatable animatable : animatables) {
animatable.updateAnimatedState();
}
}
});
}
public void add(Animatable animatable) {
animatables.add(animatable);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
}
现在,我们需要做的就是更新两个组件......
public static class ArcsPanel extends JPanel implements Animatable {
//...
@Override
public void updateAnimatedState() {
angle += DELTA;
repaint();
}
}
public class StillClock extends JPanel implements Animatable {
//...
@Override
public void updateAnimatedState() {
setCurrentTime();
repaint();
}
}
您会注意到我已经稍微修改了您的代码,以便现在两个组件都从JPanel
延伸,从JFrame
延伸是非常有限的,并且通常不鼓励。
最后,我们只需要全部设置......
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
ArcsPanel arcPanel = new ArcsPanel();
StillClock clockPanel = new StillClock();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(arcPanel);
frame.add(clockPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Engine engine = new Engine();
engine.add(arcPanel);
engine.add(clockPanel);
engine.start();
}
});
}
}
因为我知道一堆不符合上下文的代码片段会让人感到困惑......
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
ArcsPanel arcPanel = new ArcsPanel();
StillClock clockPanel = new StillClock();
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridLayout(0, 2));
frame.add(arcPanel);
frame.add(clockPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Engine engine = new Engine();
engine.add(arcPanel);
engine.add(clockPanel);
engine.start();
}
});
}
public class Engine {
private List<Animatable> animatables;
private Timer timer;
public Engine() {
animatables = new ArrayList<>(4);
timer = new Timer(10, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
for (Animatable animatable : animatables) {
animatable.updateAnimatedState();
}
}
});
}
public void add(Animatable animatable) {
animatables.add(animatable);
}
public void start() {
timer.start();
}
public void stop() {
timer.stop();
}
}
public interface Animatable {
public void updateAnimatedState();
}
public static class ArcsPanel extends JPanel implements Animatable {
protected static final float DELTA = 1.0f;
private float angle = 0;
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
int radius = (int) (Math.min(getWidth(), getHeight()) * 0.4);
g2d.setTransform(AffineTransform.getRotateInstance(Math.toRadians(angle), xCenter, yCenter));
int x = xCenter - radius;
int y = yCenter - radius;
g2d.fillArc(x, y, 2 * radius, 2 * radius, 0, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 90, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 180, 30);
g2d.fillArc(x, y, 2 * radius, 2 * radius, 270, 30);
g2d.dispose();
}
@Override
public void updateAnimatedState() {
angle += DELTA;
repaint();
}
}
public class StillClock extends JPanel implements Animatable {
private int hour;
private int minute;
private int second;
public StillClock() {
setCurrentTime();
}
public StillClock(int hour, int minute, int second) {
this.hour = hour;
this.minute = minute;
this.second = second;
}
@Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Initialize clock parameters
int clockRadius
= (int) (Math.min(getWidth(), getHeight()) * 0.8 * 0.5);
int xCenter = getWidth() / 2;
int yCenter = getHeight() / 2;
// Draw circle
g.setColor(Color.black);
g.drawOval(xCenter - clockRadius, yCenter - clockRadius,
2 * clockRadius, 2 * clockRadius);
g.drawString("12", xCenter - 5, yCenter - clockRadius + 12);
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 second 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.setColor(Color.red);
g.drawLine(xCenter, yCenter, xSecond, ySecond);
// Draw minute 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.setColor(Color.blue);
g.drawLine(xCenter, yCenter, xMinute, yMinute);
// Draw hour hand
int hLength = (int) (clockRadius * 0.5);
int xHour = (int) (xCenter + hLength
* Math.sin((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
int yHour = (int) (yCenter - hLength
* Math.cos((hour % 12 + minute / 60.0) * (2 * Math.PI / 12)));
g.setColor(Color.green);
g.drawLine(xCenter, yCenter, xHour, yHour);
}
public void setCurrentTime() {
// Construct a calendar for the current date and time
Calendar calendar = new GregorianCalendar();
// Set current hour, minute and second
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
}
@Override
public void updateAnimatedState() {
setCurrentTime();
repaint();
}
}
}