首先,我们需要使用Java的GUI库Swing来创建一个窗口,然后在窗口中心画一个圆和一个直角扇形。接着在圆内随机生成一个黑点.最后,当翻转按钮被按下时,将扇形慢慢移到黑点的位置,同时将扇形变为红色,并在控制台输出黑点的坐标和与圆心的角度。
时间: 2024-05-08 08:17:40 浏览: 77
以下是实现代码示例:
```
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FanGame extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private JButton flipBtn;
private FanPanel fanPanel;
private Random rand;
public FanGame() {
super("Fan Game");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setResizable(false);
setLocationRelativeTo(null);
rand = new Random();
fanPanel = new FanPanel();
flipBtn = new JButton("Flip");
flipBtn.addActionListener(this);
JPanel contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setLayout(null);
fanPanel.setBounds(0, 0, 400, 400);
flipBtn.setBounds(160, 360, 80, 30);
contentPane.add(fanPanel);
contentPane.add(flipBtn);
setContentPane(contentPane);
setVisible(true);
}
public static void main(String[] args) {
new FanGame();
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == flipBtn) {
fanPanel.flipToBlackDot();
}
}
}
class FanPanel extends JPanel {
private static final long serialVersionUID = 1L;
private int centerX;
private int centerY;
private int radius;
private int fanAngle;
private int fanStartAngle;
private int fanEndAngle;
private int fanStep;
private int fanX1;
private int fanY1;
private int fanX2;
private int fanY2;
private int dotX;
private int dotY;
private boolean isFanFlipped;
private Random rand;
public FanPanel() {
rand = new Random();
centerX = 200;
centerY = 200;
radius = 150;
fanAngle = 0;
fanStartAngle = 45;
fanEndAngle = 225;
fanStep = 5;
fanX1 = centerX;
fanY1 = centerY;
fanX2 = centerX;
fanY2 = centerY - radius;
isFanFlipped = false;
dotX = centerX;
dotY = centerY;
}
public void flipToBlackDot() {
if (!isFanFlipped) {
int angle = rand.nextInt(360);
double radian = Math.toRadians(angle);
dotX = (int) (centerX + (radius - 10) * Math.cos(radian));
dotY = (int) (centerY - (radius - 10) * Math.sin(radian));
fanAngle = angle + 90;
isFanFlipped = true;
repaint();
System.out.println("Black Dot: (" + dotX + ", " + dotY + ")");
System.out.println("Fan Angle: " + fanAngle);
}
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLACK);
g.drawOval(centerX - radius, centerY - radius, radius * 2, radius * 2);
g.setColor(Color.RED);
if (isFanFlipped) {
g.fillArc(centerX - radius, centerY - radius, radius * 2, radius * 2, fanStartAngle, fanAngle - fanStartAngle);
} else {
g.fillArc(centerX - radius, centerY - radius, radius * 2, radius * 2, fanStartAngle, fanEndAngle - fanStartAngle);
}
g.setColor(Color.BLACK);
g.fillOval(dotX - 5, dotY - 5, 10, 10);
}
}
```
阅读全文