我在java中遇到问题,每次在paint类中调用一个方法时,它都会更新矩形的坐标,然后绘制它。
目前,我所得到的只是更新坐标的方法。但是只显示一个矩形,这是方法更新的最后一个矩形。
如何在每次调用方法时创建一个矩形,而不仅仅是在最后一次迭代?
在我的主类中,我有以下代码从文件中读取数据。它读取一行然后调用paint类绘制矩形,然后再读取下一个
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
paint类有:
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);
}
答案 0 :(得分:3)
有两种常见的方法
查看Custom Painting Approaches以了解这两种方法的工作示例。