java画一个圆
画一个圆,不停得转动,用一个按钮控制它,点一下就停,在点一下就转,并且圆上面还要分几个区域,就像摇奖机一样,求大神们帮助,一点思路都没有
[解决办法]
所谓的转动其实是颜色的变换,根据要划分的区域,计算角度大小。先确定圆心,然后根据角度画直线,最后画弧。然后每隔一段时间重画就行了,重画的时候,注意颜色的角度的变化,由于颜色的不同,当重画的时候给你的错觉就是圆在转动了。
[解决办法]
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class CircleFrame extends JFrame{ private CirclePanel circlePanel = new CirclePanel(); private JButton btnStop = new JButton("Stop"); private CircleThread circleThread = new CircleThread(circlePanel, true); public CircleFrame() { this.setLayout(new BorderLayout()); this.add(circlePanel, BorderLayout.CENTER); this.add(btnStop, BorderLayout.SOUTH); //貌似我的电脑上North方向也出现了一个JButton,不知道是不是java虚拟机的bug btnStop.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { if (btnStop.getText().equals("Stop")) { btnStop.setText("Continue"); circleThread.setIsCircling(false); } else { btnStop.setText("Stop"); circleThread.setIsCircling(true); } } }); circleThread.start(); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { JFrame frame = new CircleFrame(); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }); }}class CirclePanel extends JPanel{ private int startAngle = 0; private int arcAngle = 90; //只有四种颜色,每种颜色占90度 public CirclePanel() { this.setPreferredSize(new Dimension(400, 400)); } public void paintComponent(Graphics g) { super.paintComponents(g); g.setColor(Color.RED); //这里为了简便,只画了四种颜色 g.fillArc(100, 100, 200, 200, startAngle, arcAngle); g.setColor(Color.YELLOW); g.fillArc(100, 100, 200, 200, startAngle + arcAngle, arcAngle); g.setColor(Color.BLUE); g.fillArc(100, 100, 200, 200, startAngle + arcAngle * 2, arcAngle); g.setColor(Color.GREEN); g.fillArc(100, 100, 200, 200, startAngle + arcAngle * 3, arcAngle); } public void setStartAngle(int startAngle) { this.startAngle = startAngle; }}class CircleThread extends Thread{ private CirclePanel circlePanel; private boolean isCircling; public CircleThread(CirclePanel circlePanel, boolean isCircling) { this.circlePanel = circlePanel; this.isCircling = isCircling; } public void setIsCircling(boolean isCircling) { this.isCircling = isCircling; } public void run() { for (int i = 0; ; i++) { while (! isCircling) //用于暂停旋转的 { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } circlePanel.setStartAngle(i % 360); //设置不同的起始旋转角度 circlePanel.repaint(); try { Thread.sleep(1); //这个是旋转每度的间隔时间,如果太小好像动画看上去会不流畅 } catch (InterruptedException e) { e.printStackTrace(); } } }}