我正在使用由嵌套循環控制的繪製方法繪製堆疊杯的小程序。我有一切工作,除了當外循環結束時,圖形消失。使用Java paint方法在while循環中執行繪製刪除
該程序由兩個While循環組成。第一個是增加圖紙的行數,第二個是抽取行中的杯子。
在調試模式下觀察程序,在最後執行外部While循環後,對外部While語句進行評估(當(baseLength> 0)爲false時,則程序上行到int counter2 = 0,繪圖消失,程序退出。
我也試圖與爲構建這一環,而不是同時,我也得到同樣的效果。一旦外環的判斷爲假,圖紙消失。
似乎油漆(g)方法做了一些我不太明白的事情,導致圖紙被抹掉。任何想法?
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Color;
public class Cups1 extends JFrame {
/*
* Declaring instance variables. startX and startY represent the top left coordinates
* of the first cup block in the bottom row. cupWidth and cupHeight represent the width
* and height of each row.
*/
int startX, startY, cupWidth, cupHeight;
int baseLength; //number of cups in bottom row
int cupSpacing; //spacing between adjacent cups
//Constructor calls constructor from JFrame class, argument is window title
public Cups1()
{
super("Example");
startX = 100;
startY = 300;
cupWidth = 25;
cupHeight = 40;
baseLength = 7;
cupSpacing = 6;
}
//Paint method fills pattern from bottom to top
public void paint(Graphics g)
{
//Call paint method of JFrame
super.paint(g);
//startX and startY are variables to set original point of reference
//drawX and drawY are local variables for each cup instance
int drawY = startY, drawX = startX;
int counter1 = 0;
while (baseLength > 0)
{
int counter2 = 0;
//Control number of cups in level
while (baseLength > counter2)
{
//Make odd levels red and even levels blue to alternate colors
if (baseLength % 2 == 0)
{
g.setColor(Color.blue);
} else {
g.setColor(Color.red);
}
//Draw cup shapes
g.fillRect(drawX, drawY, cupWidth, cupHeight);
drawX = drawX + cupWidth + cupSpacing;
counter2++;
}
//Decrement base length to reduce number of cups on next level
baseLength--;
counter1++;
//Shift x by 1/2 of the total value of cupWidth and cupSpacing
drawX = startX + (((cupWidth + cupSpacing)/2) * counter1);
//Raise height of next level by one cup height
drawY = startY - (cupHeight * counter1);
}
}
public static void main(String[] args) {
//Create application object with 550 x 550 size and visibility = true
Cups1 cup = new Cups1();
cup.setSize(550,550);
cup.setVisible(true);
//Close application by clicking "x"
cup.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
'JFrame'被設計成一個容器而不是畫布。嘗試使'Cups1'成爲'JComponent'的子類,在那裏繪製邏輯,然後將它添加到標準的'JFrame'中。 – jingx