[英]Is there a way to make a section of the paint() method only run once in Java?
我正在嘗試制作 Uno 游戲(不重要),因此我需要在游戲開始時繪制一些矩形和圖像進行設置。 但是,當點擊套牌時,它需要將一張牌添加到玩家的手上。 這顯然與原始設置的時間不同,但由於它涉及到抽卡,它是否也需要在paint() 中? 我試圖通過創建布爾值並根據是否已繪制圖形來更改它們來解決此問題,但是當我這樣做時,它現在根本不會繪制開始圖形。 有沒有更簡單的方法可以做到這一點,或者至少有解決這個問題的方法? 還有更多代碼,但我認為下面的代碼就是這個問題所需要的。 謝謝!
公共 class ImageCreator {
private boolean hasStartedDrawing = false;
private boolean drawCardPlayer = false;
public void mouseClicked(MouseEvent e)
{
if ((e.getX() >= 472 && e.getX() <= 662) && (e.getY() >= 205 && e.getY() <= 455))
{
drawCardPlayer = true;
repaint();
}
}
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
if (hasStartedDrawing == false)
{
Rectangle rect0P = new Rectangle(50, 650, 95, 125); g2.draw(rect0P);
hasStartedDrawing = true;
{
if (drawCardPlayer)
{
game.drawCardPlayer(g); //a method in another class that actually draws the card
drawCardPlayer = false;
}
}
}
你做得很好,只是一個小細節。 我一開始也很掙扎。
最好的方法是覆蓋paintComponent ,然后在每次需要更新或“繪制”GUI 時調用repaint 。 如果您需要更深入的解釋,這里有“為什么”: https://www.oracle.com/java/technologies/painting.html
And if you need some easy (but important) examples, here you have (also from Oracle Documentation): https://docs.oracle.com/javase/tutorial/uiswing/painting/index.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.