日期:2014-05-20 浏览次数:20938 次
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(); } } } }