在paintComponent()方法中,变量没有改变

时间:2014-09-05 22:46:46

标签: java swing methods null graphics2d

让我们说我做了一个简单的图形应用程序。它有两个类,主类和第二个类,称为“面板”,它扩展了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似乎都没有变化。 main方法的while循环中的代码永远不会最终绘制一个矩形,尽管paintComponent()方法将其矩形绘制得很好。在主要方法中,testg2g似乎始终分别为falsenull。我在这里错过了什么?无论如何在paintComponent()方法之外使用graphics2D?

2 个答案:

答案 0 :(得分:1)

摆脱while (true)阻止,不需要它,它有害,因为它有可能在你的GUI线程上踩踏板。而是在您的JFrame上调用setVisible(true) 之前添加您的JPanel

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

所以回答,

  

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

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

答案 1 :(得分:0)

尝试使用相同的代码覆盖此方法:

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

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

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