以下将提供一个Java Swing程序示例,来创建一个包含各种食物项目的旋转转盘。用户可以通过点击转盘来随机旋转到不同的位置。
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
public class SpinFoodWheel extends JFrame {
private final int circleRadius = 200; // 圆的半径
private final List<String> foods = new ArrayList<>();
private final float angleStep = (float) Math.toRadians(360.0 / NUMBER_OF_SECTIONS); // 分隔角度
private double currentAngle = 0; // 当前指针角度
public SpinFoodWheel() {
setTitle("美味食品旋转盘");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// 添加转盘画板组件
add(new FoodPanel());
setLocationRelativeTo(null); // 居中显示
setVisible(true);
}
// 自定义画板以绘制转盘和食物
private class FoodPanel extends JPanel {
public FoodPanel() {
setPreferredSize(new Dimension(circleRadius * 2, circleRadius * 2));
addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
spinWheel();
}
});
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawWheel(g);
}
private void drawWheel(Graphics g) {
int numFoods = generateFoods();
if (numFoods < 1) return;
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
int numSections = foods.size();
Graphics2D g2d = (Graphics2D) g;
g2d.translate(centerX, centerY);
// 绘制颜色区块、文字和指针
for (int i = 0; i < numSections; i++) {
double angleRad = Math.toRadians(currentAngle + i * 360.0 / numSections);
g2d.setPaintgetColor(.hsbToRgb((float)(i * 1.0 / numSections), 1, 1)); // 根据HSL模型随机颜色
g2d.fillArc(-circleRadius / 2, -circleRadius / 2, circleRadius, circleRadius, 360 * i / numSections, 360 / numSections);
// 计算文本的位置并绘制食物名称
String text = foods.get(i % numFoods);
FontMetrics fm = g.getFontMetrics();
int textWidth = fm.stringWidth(text);
int x = (int) (circleRadius * 0.8 * Math.cos(angleRad));
int y = (int) (circleRadius * 0.8 * Math.sin(angleRad)) - (int) (fm.getHeight() * 0.4);
g.drawString(text, x - textWidth / 2, y + fm.getAscent() / 2);
if(i == numSections - 1){
drawCenterPointer();
}
}
g2d.translate(-centerX, -centerY);
}
private int generateFoods() {
foods.clear();
for (int i = 0; i < NUMBER_OF_SECTIONS; i++) {
foods.add(FOODS[Math.abs(i) % FOODS.length]);
}
return NUMBER_OF_SECTIONS;
}
private void spinWheel() {
currentAngle = Math.toRadians(ThreadLocalRandom.current().nextInt(360));
repaint();
}
private void drawCenterPointer() {
Graphics2D g2d = (Graphics2D) getGraphics();
g2d.setPaint(Color.BLACK);
g2d.drawLine(0, 0, 5, 0);
g2d.rotate(Math.toRadians(270));
g2d.drawLine(0, 0, 5, 0);
}
private Color getColor(float h, float s, float b) {
return Color.getHSBColor(h, s, b);
}
}
private static final int NUMBER_OF_SECTIONS = 8; // 分区数量
private static final String[] FOODS = {"炸鸡", "汉堡", "披萨", "寿司", "雪糕", "沙拉"};
public static void main(String[] args) {
new SpinFoodWheel();
}
}
FOODS
和转盘分区数NUMBER_OF_SECTIONS
可以根据需要进行调整。spinWheel()
方法通过改变`current