import java.beans.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import javax.swing.*; import javax.swing.plaf.LayerUI; class WaitingLayerUI extends LayerUI { private boolean isRunning; private Timer timer; private int angle; public void paint(Graphics g, JComponent c) { super.paint(g, c); int w = c.getWidth(); int h = c.getHeight(); if (!isRunning) return; Graphics2D g2 = (Graphics2D)g.create(); Composite urComposite = g2.getComposite(); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, .5f)); g2.fillRect(0, 0, w, h); g2.setComposite(urComposite); int s = Math.min(w , h) / 5; int cx = w / 2; int cy = h / 2; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON); g2.setStroke( new BasicStroke(s / 2 , BasicStroke.CAP_ROUND , BasicStroke.JOIN_ROUND)); g2.setPaint(Color.BLUE); g2.rotate(Math.PI * angle / 180, cx, cy); for (int i = 0; i < 12; i++) { float scale = (11.0f - (float)i) / 11.0f; g2.drawLine(cx + s, cy, cx + s * 2, cy); g2.rotate(-Math.PI / 6, cx, cy); g2.setComposite(AlphaComposite.getInstance( AlphaComposite.SRC_OVER, scale)); } g2.dispose(); } public void start() { if (isRunning) return; isRunning = true; timer = new Timer(100, e -> { if (isRunning) { firePropertyChange("crazyitFlag", 0 , 1); angle += 6; if (angle >= 360) angle = 0; } }); timer.start(); } public void stop() { isRunning = false; firePropertyChange("crazyitFlag", 0 , 1); timer.stop(); } public void applyPropertyChange(PropertyChangeEvent pce , JLayer layer) { if (pce.getPropertyName().equals("crazyitFlag")) { layer.repaint(); } } } public class WaitingJLayerTest { public void init() { JFrame f = new JFrame("转动的“齿轮”"); JPanel p = new JPanel(); ButtonGroup group = new ButtonGroup(); JRadioButton radioButton; p.add(radioButton = new JRadioButton("网购购买", true)); group.add(radioButton); p.add(radioButton = new JRadioButton("书店购买")); group.add(radioButton); p.add(radioButton = new JRadioButton("图书馆借阅")); group.add(radioButton); p.add(new JCheckBox("疯狂Java讲义")); p.add(new JCheckBox("疯狂Android讲义")); p.add(new JCheckBox("疯狂Ajax讲义")); p.add(new JCheckBox("轻量级Java EE企业应用")); JButton orderButton = new JButton("投票"); p.add(orderButton); final WaitingLayerUI layerUI = new WaitingLayerUI(); JLayer layer = new JLayer(p, layerUI); final Timer stopper = new Timer(4000, ae -> layerUI.stop()); stopper.setRepeats(false); orderButton.addActionListener(ae -> { layerUI.start(); if (!stopper.isRunning()) { stopper.start(); } }); f.add(layer); f.setSize(300, 170); f.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); f.setVisible (true); } public static void main(String[] args) { new WaitingJLayerTest().init(); } }