我写了一个图像旋转的代码
- Java code
import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics;import javax.swing.JPanel;public class Circle extends JPanel{ public int value; public Circle(){ } public Circle(int value){ this.value = value; } public int getValue(){ return value; } public void setValue(int value){ this.value = value; repaint(); } protected void paintComponent(Graphics g){ super.paintComponent(g); int clockRadius = (int)(Math.min(getWidth(), getHeight())*0.8*0.5); int xCenter = getWidth()/2; int yCenter = getHeight()/2; g.setColor(Color.RED); g.drawOval(xCenter-clockRadius, yCenter-clockRadius, 2*clockRadius, 2*clockRadius); int line1 = (int)(clockRadius); int line1X = (int) (xCenter-clockRadius*Math.cos(value*(2*Math.PI/60))); int line1Y = yCenter+value; g.drawLine(xCenter, yCenter, line1X, line1Y); } public Dimension getPreferredSize() { return new Dimension(100,100); } }
在运行程序时通过滑动条修改value的值,但是图像并没有发生改变,我在调试中发现滑动条移动时value的值是在改变的,但是line1X 和line1Y 的值并没有变,这是怎么回事呢,是repaint没起作用吗
------解决方案--------------------------------------------------------
方法名
paintComponent
改成
paintComponents
------解决方案--------------------------------------------------------
- Java code
public static void main(String[] args) throws Exception { JFrame app = new JFrame("测试"); app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); app.setSize(400, 500); Circle panel = new Circle(20); app.add(panel); app.setVisible(true); for(int i = 0;i<100;i++) { Thread.sleep(100); panel.setValue(20 + i*5); } }