![](/img/trans.png)
[英]Why doesn't repaint() in the draw() method work (doesn't call paint())?
[英]Repaint() method doesn't call draw()
基本上,我有一個具有Shape draw()
和animate()
方法的Shape接口。 每個將繪制形狀的類都將實現此目的。 還有另一個類,其中包含這些Shape類的arrayList
。 然后有一個單獨的類,其中包含我的JFrame。 我有一個“動畫”按鈕,它調用該arrayList
所有animate()
方法。
我正在使用netbeans
,它表示我沒有錯誤。 draw()
方法可以完美地工作。 這是我遇到問題的動畫。 我已經調試了它,顯然, repaint()
方法沒有調用其他任何東西,這就是為什么所有形狀都不動畫/移動的原因。 它找不到draw()
方法,因此不會重繪它。
這是我的代碼:
這是我的形狀之一
public class Circle extends Canvas implements Shape{
int xpos, ypos, diam;
GradientPaint color;
public Circle(){
xpos = 103;
ypos = 88;
diam = 140;
color = new GradientPaint(0, 0, new Color(204, 204, 254),
120, 100, new Color(255, 255, 255), true);
}
@Override
public void draw(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setPaint(color);
g.fillOval(xpos, ypos, diam, diam);
}
@Override
public void animate(){
xpos += 10;
ypos += 10;
repaint();
}
}
這包含我的arrays of Shapes
public class ShapeCanvas extends Canvas { private ArrayList list; public ShapeCanvas(){ setBackground(Color.WHITE); setSize(1000, 700); list = new ArrayList<>(); Circle circle = new Circle(); list.add(circle);} //calls all draw() method @Override public void paint(Graphics g){ for (int i = 0; i < list.size(); i++){ list.get(i).draw(g); } } //this method calls all animate() method public void animateAll(){ for (int i = 0; i < list.size(); i++){ list.get(i).animate(); } }
}
And this here is my JFrame
public class Animation extends JFrame{ public Animation(){ setLayout(new BorderLayout()); final ShapeCanvas sc = new ShapeCanvas(); JButton animate = new JButton("Animate"); animate.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent ae){ sc.animateAll(); } }); add(sc, "Center"); add(animate, "South"); } public static void main(String[] args) { Animation g = new Animation(); g.setVisible(true); g.setSize( 1000, 700 ); g.setTitle( "Animation" ); g.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); g.setResizable(false); } }
我試過使用JPanel
或JLayeredPane
,嘗試使用revalidate(),validate()甚至invalidate()
。 許多人建議使用一個可以調用super.paintComponent()的paintComponent(),但是有什么方法可以在不刪除/替換draw()
方法的情況下進行呢? 雖然,我可能只是缺少一些重要的細節。 。 。
顯然,很多人已經在這里問過這個,而我已經閱讀了其中的大多數內容。 很抱歉,我很多余。 但是任何幫助或建議,我們將不勝感激!
編輯:我解決了! 感謝大伙們!
根據我的理解(僅限於上學期的課程),您需要重寫paintComponent並調用子組件的draw函數。 repaint()調用paintComponent。
這是我上學期教授的示例代碼。 我發現他的代碼非常清晰,易於提取。 http://students.cs.byu.edu/~cs240ta/fall2013/rodham_files/week-09/graphics-programming/code/Drawing/src/noevents/DrawingComponent.java
我知道您的編輯說您已修復它,但我想確定並指出OP中代碼的問題。 據我所知, Circle
不應擴展Canvas
。 在動畫中,它調用重繪,但是重繪無處可做,因為它沒有作為組件添加到任何地方。
更正看起來像這樣:
class Circle implements Shape {
@Override
void animate() {
/* only set positions */
}
}
class ShapeCanvas extends Canvas {
@Override
void animateAll() {
for(/* all shapes */) {
/* call shape.animate() */
}
/* repaint this Canvas */
repaint();
}
}
另外,我也同意@AndrewThompson的觀點,幾乎沒有理由在Swing上使用AWT。 特別是如果您想將兩者混合在一起,那就不要。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.