【问题标题】:Variables not changed when in paintComponent() method在 paintComponent() 方法中变量未更改
【发布时间】:2014-09-05 22:46:45
【问题描述】:

假设我制作了一个简单的图形应用程序。它有两个类,主类和扩展 JPanel 的称为“面板”的第二个类。 主类只是一个包含 JPanel 的 JFrame。以下是它的内容:

public static Panel panel = new Panel();

public static void main(String[] args) {
    JPanel p = new Panel();
    JFrame fr = new JFrame();
    fr.setSize(600, 600);
    fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    fr.setLocationRelativeTo(null);
    fr.setVisible(true);
    fr.add(p);
    while (true) {
        fr.repaint();
        if (panel.test) panel.g2d.drawRect(30, 30, 40, 40);
    }
}

第二个类使用 Graphics2D 创建 JPanel 的内容。它还具有在paintComponent() 方法中更改的变量。以下是它的内容:

Graphics2D g2d;
boolean test = false;

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g2d = (Graphics2D) g;
    test = true;
    g2d.setColor(Color.RED);
    g2d.drawRect(10, 10, 20, 20);
}

但是,问题是:在paintComponent() 方法执行后,testg2g 似乎都没有改变。尽管 paintComponent() 方法可以很好地绘制矩形,但 main 方法的 while 循环中的代码永远不会绘制矩形。在 main 方法中,testg2g 似乎总是分别为 falsenull。我在这里想念什么?无论如何在paintComponent()方法之外使用graphics2D?

【问题讨论】:

    标签: java swing methods null graphics2d


    【解决方案1】:

    摆脱 while (true) 块,它不是必需的,而且它是有害的,因为它有可能踩到你的 GUI 线程。而是添加您的 JPanel before 在您的 JFrame 上调用 setVisible(true)

    此外,创建 Graphics2D 字段并尝试在 paintComponent 之外使用它进行绘制会引发 NullPointerException。了解您无法完全控制 Swing Graphics,并且不应尝试提取 Graphics 对象或以这种方式进行绘制。您将需要阅读 Swing 图形教程以了解如何正确使用 Swing 组件进行绘制。

    所以回答,

    还有没有在paintComponent()方法之外使用graphics2D?

    没有。您可以通过使用 BufferedImage 的 Graphics 对象进行绘制来解决此问题,但是您仍然需要将 BufferedImage 绘制到您的 JPanel 或 JComponent 的 paintComponent 方法。

    【讨论】:

    • 进行了上述更改,但问题仍然存在
    • @SuperNew:如果您对代码进行了更改,请将您的新代码发布为对原始问题的修改。不要摆脱你的原始代码,而是在它下面添加新代码。也显示更多您的代码。也不要将任何类命名为“Panel”,因为它会与核心 Java 类名发生冲突。另外,你读过教程了吗?
    【解决方案2】:

    也尝试用相同的代码覆盖这个方法:

                @Override
                public void paintComponents(Graphics grphcs)
                {
                    super.paintComponents(grphcs);
                    //add code here
                }
    

    而且我还建议不要使用 JPanel 指针指向 awt Panel 变量。 所以改变:

           `JPanel p = new Panel();  to `JPanel p = new JPanel();` 
    

    【讨论】:

      猜你喜欢
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多