我正在尝试编写一个代码,只需单击一个点,两行三角形,三个三角形,然后重新启动4,但我第一次点击时仍然会得到nullpointerexception。这是我的代码:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TriangleClicker extends JFrame {
private final int width = 700;
private final int height = 800;
private JPanel panel;
private MouseListener listener;
private int p1x;
private int p1y;
private int p2x;
private int p2y;
private int p3x;
private int p3y;
private int count = 0;
private JComponent tri;
public TriangleClicker() {
this.setSize(width, height);
this.add(createPanel());
this.tri = new MousePressListener();
this.add(this.tri);
listener = new MousePressListener();
this.addMouseListener(listener);
}
public JPanel createPanel() {
panel = new JPanel();
panel.setSize(width, height);
return panel;
}
class MousePressListener extends JComponent implements MouseListener {
public Graphics g;
public void drawLine1(Graphics g) {
g.setColor(Color.BLACK);
g.drawLine(p1x, p1y, p1x, p1y);
}
public void drawLine2(Graphics g) {
g.drawLine(p1x, p1y, p2x, p2y);
}
public void drawLine3(Graphics g) {
g.drawLine(p3x, p3y, p1x, p1y);
g.drawLine(p3x, p3y, p2x, p2y);
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
if (count == 0) {
System.out.println("1");
p1x = e.getX();
p1y = e.getY();
drawLine1(g);
count++;
}
else if (count == 1) {
p2x = e.getX();
p2y = e.getY();
drawLine2(g);
count++;
}
else if(count == 2) {
p3x = e.getX();
p3y = e.getY();
drawLine3(g);
count++;
}
else if(count == 4) {
g.clearRect(0, 0, WIDTH, HEIGHT);
p1x = e.getX();
p1y = e.getY();
p2x = 0;
p2y = 0;
p3x = 0;
p3y = 0;
drawLine1(g);
count = 1;
}
}
@Override
public void mouseReleased(MouseEvent e) {
}
}
}
我的错误在makeLine1()方法中尝试将颜色设置为黑色,并在mousePressed()方法中尝试调用makeLine1()。
感谢。