【发布时间】:2015-04-21 15:29:11
【问题描述】:
我在 java 中遇到一个问题,每次在绘制类中调用一个方法时,它都会更新矩形的坐标,然后应该绘制它。
目前,我得到的只是更新坐标的方法。但是只显示一个矩形,这是方法更新的最后一个。
我怎样才能在每次调用方法时创建一个矩形,而不仅仅是在最后一次迭代时?
在我的主类中,我有以下从文件中读取数据的代码。它读取一行,然后调用绘制类来绘制矩形,然后再读取下一行
try (BufferedReader br = new BufferedReader(new FileReader("numbers.txt")))
{
String line;
while ((line = br.readLine()) != null) {
int change2Int=Integer.parseInt(line.trim());
mp.getDataForDisplay(change2Int);//send to paint class
}
}
catch (Exception expe)
{
expe.printStackTrace();
}
文件 numbers.txt 只是包含:
0
3
5
2
绘画类有:
class mainPanel extends JPanel
{
int processes, storedProcesses;
// for rectangles
int xCoor =0;
int yCoor =0;
int width =10;
int height =50;
static int x = 100;
int [] y = {100,150,200,250,300,350,400,450,500,550};
//constructor and other irrelevant methods here
public void getDataForDisplay (int proc)
{
//the method checks the value from "proc" to see where to display a rectangle on screen. Only prints last rectangle to screen
int loop = 0;
while (loop <= storedProcesses)
{
if (proc == loop)
{
xCoor = x;
yCoor = y[loop];
x = x + 10;
System.out.println("right");
repaint();
}
else
{
System.out.println("wrong");
}
loop++;
}
System.out.println("OK WERE HERE");
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect (xCoor, yCoor, width, height);
}
【问题讨论】:
-
'storeProc' 存储什么值? 'while' 和 'if' 条件是否符合值?
-
它从一个文本文件中读取一个 INT,如上所示