如何延迟Java代码直到代码的另一部分完成?

问题描述 投票:2回答:3

所以我正在尝试java.awt.Graphics库,并在我的代码中遇到了一个问题。下面的代码返回空指针异常,因为在执行时没有定义Graphics对象“g”。我可以循环调用并检查g!= null但是有更好的方法吗?

谢谢你的帮助。

这是我的代码:

package gui;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Gui extends JPanel{

Graphics g;

public Gui() 
{
    JFrame frame = new JFrame("test");
    frame.setSize(700, 700);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setVisible(true);
    frame.add(this);
}

public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    this.g = g;

    g.setColor(Color.blue);

    for(int x = 0;x < 700; x += 20) 
    {
        g.drawLine(x, 0, x, 700);
    }

    for(int y = 0;y < 700; y += 20) 
    {
        g.drawLine(0, y, 700, y);
    }
}

public void draw(Tuple xy) 
{
    g.setColor(Color.blue);   // <--- null pointer exception
    g.fillOval(xy.x, xy.y, 5, 5);
}

}

和主要类:

package gui;

public class Main {

public static void main(String[] args)
{

    new Gui().draw(new Tuple(200,200)); //Tuple is a custom class I wrote

}
}
java nullpointerexception paintcomponent
3个回答
2
投票

找到了我的null问题的解决方案。我修改了方法“draw()”来接受一个元组,然后将它传递给paintComponent()函数并调用repaint()。

package gui;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class Gui extends JPanel{

    Graphics g;
    Tuple xy;

    public Gui() 
    {
        JFrame frame = new JFrame("test");
        frame.setSize(700, 700);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setLocationRelativeTo(null);
        frame.add(this);
    }

    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        this.g = g;

        g.setColor(Color.blue);

        for(int x = 0;x < 700; x += 20) 
        {
            g.drawLine(x, 0, x, 700);
        }

        for(int y = 0;y < 700; y += 20) 
        {
            g.drawLine(0, y, 700, y);
        }

        if(xy != null) 
        {
            g.fillOval(xy.x, xy.y, 5, 5);
        }
    }

    public void draw(Tuple xy)
    {
        this.xy = xy;
        repaint();
    }

}

谢谢你的帮助


1
投票

你应该做所有的绘图

public void paintComponent(Graphics g) 

https://docs.oracle.com/javase/tutorial/uiswing/painting/problems.html上陈述的方法。


-1
投票

使用回调函数。比polling更好的财产。你得到一个新的图形对象。并且您的调用将在适当的上下文中执行。

这是一般的想法:

Instantiation

new Gui((Graphics graphics)-> {
   // your code here
});

CTOR or Init function

public Gui(GraphicsCallback callback) 

Invoke

调用回调。如果它适合您的用例,您可以检查是否调用并仅回调一次。或者回调实现可以管理被调用的多次时间。

public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    this.g = g;
    this.callback(g)
© www.soinside.com 2019 - 2024. All rights reserved.