以下是一个利用Java Swing以及2D Graphics API实现的可旋转转盘的示例代码。需要注意的是,这段代码实现了转盘的界面绘制和旋转效果,并通过按钮进行控制。转盘分为几块不同颜色的部分,并在每个部分中随机放置了一些食物的名称。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class FoodSpinWheel extends JFrame {
private static final int WHEEL_SLICES = 6;
private static final String[] COLORS = {"RED", "BLUE", "GREEN", "YELLOW", "ORANGE", "PURPLE"};
private static final String[] FOODS = {"炸鸡", "汉堡", "披萨", "寿司", "雪糕", "沙拉", "烧烤", "蛋糕", "水果", "热狗"};
private static final int WHEEL_RADIUS = 200;
private double angle = 0;
public FoodSpinWheel() {
setTitle("幸运食物转盘");
setSize(700, 700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
// 设置布局管理器为null,这样可以完全使用绝对定位
setLayout(null);
final JButton spinButton = new JButton("转动");
spinButton.setBounds(250, 500, 200, 50);
getContentPane().add(spinButton);
// 添加按钮事件监听
spinButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
rotateWheel();
}
});
// 添加自定义画板Panel
FoodPanel foodPanel = new FoodPanel();
foodPanel.setBounds(50, 50, 600, 400);
getContentPane().add(foodPanel);
}
private void rotateWheel() {
angle = (angle + 90) % 360; // Rotate the wheel 90 degrees each press
// 重新绘制Panel
repaint();
}
// 自定义Panel,用于绘制转盘
class FoodPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawWheel(g);
}
private void drawWheel(Graphics g) {
int centerX = getWidth() / 2;
int centerY = getHeight() / 2;
// 设置抗锯齿渲染
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.translate(centerX, centerY);
int width = getWidth() - 100;
int height = getHeight() - 100;
// 以指定的半径绘制圆形转盘
for (int i = 0; i < WHEEL_SLICES; i++) {
// 设置扇形区域的颜色
g.setColor(Color.decode(COLOR(i)));
int startAngle = i * 360 / WHEEL_SLICES + (int) (angle);
int arcAngle = 360 / WHEEL_SLICES;
g.fillArc(-width / 2, -height / 2, width, height, startAngle, arcAngle);
// 计算文本的位置并绘制食物名称
Font font = new Font("宋体", Font.PLAIN, 20);
g.setFont(font);
FontMetrics fm = g.getFontMetrics();
String text = FOODS[(i + angle / 90) % FOODS.length];
int textWidth = fm.stringWidth(text);
int textHeight = fm.getHeight();
g.drawString(text, -textWidth / 2, -height / 2 + (height - textHeight) / (WHEEL_SLICES / 2) + i * (height - textHeight) / WHEEL_SLICES);
}
g.drawOval(-width / 2, -height / 2, width, height); // Draw border circle
g.translate(-centerX, -centerY); // Translate back
}
private Color.ColorSpace color; // Used in COLORS array
private Object COLOR(int index) {
return COLORS[Math.abs(index + (1 << 30)) % COLORS.length];
}
}
public static void main(String[] args) {
new FoodSpinWheel();
}
}
这段代码设置了一个FoodSpinWheel
类来绘制带有一个按钮的窗口,点击按钮将旋转转盘angle
角度,并使面板重新绘制。转盘被设计成分为六个扇区,每个扇区对应一个颜色和一个食物元素。
为了获得所需的旋转效果,请确保在实际环境中运行,并根据需要调整颜色和食物项目等参数。