我正在尝试使用一个扩展MouseInputAdapter
来绘制自由形状的类,稍后我可能会制作一个动画对象。
我已经看到了一些答案,但他们正在使用addMouseMotionListener(this)
,据我所知,你不能用一个对象来做。我的主要问题实际上是画一些东西。我可能缺少一些基本的东西,比如在哪里初始化我的JPanel
或在动画方法中添加我的监听器。nullPointerException
每次我假设它重新粉刷时,我都会得到 s。无论是那个还是每次 mouseDragged 激活。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.MouseInputAdapter;
import java.util.*;
public class test {
JFrame frame = new JFrame("Bouncing Vertices");
MyDrawPanel drawPanel = new MyDrawPanel();
private int delay = 5;
public int z = 0;
public int a = 0;
public static int counter = 0;
public static int[] xs;
public static int[] ys;
public static boolean isDone = false;
public void animate() {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(drawPanel);
frame.setSize(800, 600);
frame.setVisible(true);
MyListener alpha = new MyListener();
drawPanel.addMouseMotionListener(alpha);
drawPanel.addMouseListener(alpha);
while (true) {
drawPanel.repaint();
try {
Thread.sleep(delay);
} catch (Exception ex) {
}
}
}
private class MyListener extends MouseInputAdapter {
public void mouseDragged(MouseEvent arg0) {
int x = arg0.getX();
int y = arg0.getY();
if (x != z || y != a) {
xs[counter] = x;
ys[counter] = y;
z = x;
a = y;
counter++;
}
}
public void mouseReleased(MouseEvent arg0) {
isDone = true;
}
}
public static int[] getXs() {
return xs;
}
public static int[] getYs() {
return ys;
}
public static boolean getBoolean() {
return isDone;
}
public static void setBoolean() {
isDone = false;
}
public static void setArrays() {
for (int i = 0; i < ys.length; i++) {
xs[counter] = 0;
ys[counter] = 0;
}
}
public static void main(String[] args) {
test qwerty = new test();
qwerty.animate();
}
}
class MyDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
g.setColor(Color.GRAY);
g.fillRect(0, 0, this.getWidth(), this.getHeight());
if (test.getBoolean() && test.getXs().length > 0) {
g.setColor(Color.BLACK);
g.drawPolyline(test.getXs(), test.getYs(), test.getYs().length);
test.setBoolean();
test.setArrays();
}
}
}