【问题标题】:Paint rectangle each time a method is called每次调用方法时绘制矩形
【发布时间】: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,如上所示

标签: java swing


【解决方案1】:

有两种常见的方法

  1. 您需要保留一个要绘制的矩形列表,并且每次都遍历该列表。
  2. 将 Rectangle 绘制到 BufferedImage 并绘制 BufferedImage。

查看Custom Painting Approaches 了解这两种方法的工作示例。

【讨论】:

  • 我或多或少地使用第一点。我以为我在保留一份清单?
  • @lecardo, I thought I was keeping a list? 也许你是,但你的 paintComponent() 方法不会遍历列表。您专门对一个绘画语句进行硬编码,因此只有一个对象会被绘画。如果要绘制多个对象,则需要遍历列表。看看我提供的例子。
  • 如果你能试一试,有可能吗?我在这里运气不好=/
  • 我完全不知道你的代码在做什么。我为您提供了一些工作示例,展示了如何将对象添加到列表中,然后绘制该对象。我不知道你对我的工作示例有什么困惑。您需要将代码重组为与我的示例类似(不完全)的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-30
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多