绘制绘画方法 - Java

时间:2016-10-31 00:10:30

标签: java

我只发布相关代码。我对java很新,现在我正在构建一个允许用户使用draw方法的程序。但是,当我单击界面中的绘图按钮时,它会自动在页面的任何位置生成随机行,并且不允许用户交互。我认为错误发生在我的mouseListener方法中,但我不确定,因为这是我第一次做这样的事情。任何帮助将不胜感激。谢谢!

此外,打印出的错误是:线程“AWT-EventQueue-0”中的异常java.lang.NullPointerException

public class SimplePaint extends JFrame {

    JButton drawing = new JButton();
    Line2D draw = new Line2D.Float();
    Point start = null;
    Point end = null;

public SimplePaint() {
    JPanel panel = new JPanel() {  
      {
          addMouseListener(new MouseAdapter() {
              public void mousePressed(MouseEvent e) {
                  start = e.getPoint();  
              }

              public void mouseReleased(MouseEvent e) {
                  start = e.getPoint();
                  //start = null;
              }
          });
          addMouseMotionListener(new MouseMotionAdapter() {
              public void mouseMoved(MouseEvent e) {
                  end = e.getPoint();
              }

              public void mouseDragged(MouseEvent e) {
                  end = e.getPoint();
                  repaint();
              }
          });
      }
  };

drawing.setText("Draw");
panel.add(drawing);

ActionListener actionListener = new ActionListener() {     
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == drawing) {
        draw = new Line2D.Float(start.x, start.y, end.x, end.y);
        }
        repaint();
    }
};

drawing.addActionListener(actionListener);

}

public void paint(Graphics g) {
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    Line2D line = new Line2D.Float(0, 250, 2000, 300);
    g2.draw(draw);
}
}

0 个答案:

没有答案