Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

swing - Java - repainting JPanel gives an error

I'm a beginner in Java, and I'm trying to create an application that draws a rectangle where ever the cursor is located. I've already done everything, but I can't get the mouseMoved(MouseEvent) method to repaint the JPanel. Without the repaint, the rectangle is only drawn once and that's it. With the repaint, it compiles fine, but when I run it, every time the mouse is moved, I get this big "Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException" error.

So, can anyone please help me out on this?

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;

public class Game extends JPanel implements MouseMotionListener 
{
    public static void main(String[] args) {
        new Game().game();
    }
    JPanel panel;
    JButton button2;
    JButton button;
    public void game() {
        JPanel panel = new Game();
        button = new JButton("Ok");
        panel.setLayout(new FlowLayout());
        panel.add(button);

        button2 = new JButton("Cancel");

        JFrame frame = new JFrame("Game");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,500);
        frame.setResizable(false);
        frame.add(panel);

        frame.setVisible(true); 
        panel.addMouseMotionListener(this);
    }

    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        PointerInfo a = MouseInfo.getPointerInfo();
        Point b = a.getLocation();
        int x = (int) b.getX();
        int y = (int) b.getY();
        g.fillRect(x,y,100,100);        
    }

    public void mouseMoved(MouseEvent evt) {
        panel.repaint; //This is the line of code that I need help with. Thanks!
    }
    public void mouseDragged(MouseEvent evt) {}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Change this :

public void game() {
JPanel panel = new Game();

to this :

public void game() {
panel = new Game();

You are just creating a local variable in the first case. To fix this you need to instantiate the class variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...