得到一个错误,我无法看到什么

时间:2014-08-09 18:23:51

标签: java swing nullpointerexception

当我尝试通过按下按钮创建新对象时出现错误。帮助和解释将是欣赏我的猜测是一个胭脂()某处?或者其他什么很容易发现但我没有看到它

public class Main extends JFrame {
int GWIDTH = 400;
int GHEIGHT = 300;

private Image dbImage;
private Graphics dbg;

int x,y;
int rectX, rectY;
int random;

boolean mouseOnScreen;
boolean mouseDragged;

int click = 0;
int Resource = 0;
int ore = 100; 

int mx, my;


public Main(){

    setSize(GWIDTH, GHEIGHT);
    setTitle("Game");
    setResizable(false);
    setVisible(true);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    addMouseListener(new Mouse());



    frame(dbg);



    x = 0;
    y = 0;

    random = 100;

}

private void frame(Graphics g) {
     JFrame f = new JFrame();
     f.setVisible(true);
     f.setSize(400, 400);

     JPanel p = new JPanel();
     JButton b1 = new JButton("New ore");
     JButton b2 = new JButton("New worker");
     JButton b3 = new JButton("Upgrade pick");
     JButton b4 = new JButton("Turret");
     JButton b5 = new JButton("Barrack");
     b1.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
             JOptionPane.showMessageDialog(null,"Succses!");
             System.out.println(Resource-=ore);
             Rectangle r3 = new Rectangle(300, 50, 50, 50);
             g.setColor(Color.RED);
             g.fillRect(r3.x, r3.y, r3.width, r3.height);
         }
     });
     p.add(b1);
     p.add(b2);
     p.add(b3);
     p.add(b4);
     p.add(b5);
     f.add(p);
}

public class Mouse extends MouseAdapter implements MouseMotionListener {
    @Override
    public void mousePressed(MouseEvent e){
        click += e.getClickCount();
        rectX = e.getX();
        rectY = e.getY();
        y = rectY;
        x = rectX;

        Rectangle r1 = new Rectangle(rectX, rectY, 7, 7);
        Rectangle r2 = new Rectangle(175, 75, 50, 50);





        if(r1.intersects(r2))
        Resource += e.getClickCount();






    }
    @Override
    public void mouseReleased(MouseEvent e){

}

    @Override
    public void mouseEntered(MouseEvent e){
        mouseOnScreen = true;

        rectX = e.getX();
        rectY = e.getY();
    }
    @Override
    public void mouseExited(MouseEvent e){
        mouseOnScreen = false;
        rectX = e.getX();
        rectY = e.getY();
    }
    @Override
    public void mouseDragged(MouseEvent e){
        click += e.getClickCount();
        rectX = e.getX();
        rectY = e.getY();

        mouseDragged = true;


        e.consume();
    }
    @Override
    public void mouseMoved(MouseEvent e){
        rectX = e.getX();
        rectY = e.getY();


        e.consume();
    }
}



    public void paint(Graphics g){
        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, 0, 0, this);
    }


    public void paintComponent(Graphics g){
    g.fillOval(x, y, 7, 7);
    g.setColor(Color.red);
    g.drawString("Clicks ("+click+")", 40, 40);

    Rectangle r1 = new Rectangle(rectX, rectY, 7, 7);
    Rectangle r2 = new Rectangle(175, 75, 50, 50);
    Rectangle r3 = new Rectangle(300, 50, 50, 20);



    g.setColor(Color.RED);
    g.fillRect(r2.x, r2.y, r2.width, r2.height);

    g.setColor(Color.BLUE);
    g.fillRect(r1.x, r1.y, r1.width, r1.height);








        g.drawString("Resources:("+Resource+")", 40, 50);


    repaint();
}







public static void main (String[] args) {
   Main main = new Main();
}
}

这是我的错误

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at main.Main$1.actionPerformed(Main.java:80)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6527)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6292)
at java.awt.Container.processEvent(Container.java:2234)
at java.awt.Component.dispatchEventImpl(Component.java:4883)
at java.awt.Container.dispatchEventImpl(Container.java:2292)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
at java.awt.Container.dispatchEventImpl(Container.java:2278)
at java.awt.Window.dispatchEventImpl(Window.java:2739)
at java.awt.Component.dispatchEvent(Component.java:4705)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:746)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:719)
at java.awt.EventQueue$4.run(EventQueue.java:717)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:716)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

1 个答案:

答案 0 :(得分:3)

正如我所怀疑的(请参阅我对原始问题的评论之一),您正在错误地使用Graphics对象并尝试使用null Graphics变量进行绘制。建议:

  • 不要给你的类一个Graphics字段,也不要像你想要的那样将Graphics对象传递给frame方法。
  • 而是使用JVM为您提供的Graphics对象在paintComponent方法内部绘制。
  • 或者使用从BufferedImage或其他图像中提取的Graphics对象进行绘制,但是如果这样做,请确保在完成后处理Graphics对象。
  • 同样,最重要的是,您需要学习如何调试NPE的一般概念(NullPointerException)。 您应该仔细检查抛出异常的行,找出哪个变量为null,然后追溯到您的代码中以查看原因。你会一次又一次地遇到这些,相信我。

  • 此外,不要在paintComponent方法中调用repaint(),因为这是一种非常糟糕且不受控制的尝试动画的方法。如果你想要简单的动画,请使用Swing Timer。
  • 要获得更多更好的帮助,请尝试向我们提供有关您尝试使用此代码执行操作的更多详细信息。
  • 如果您的目标是让一个类将一个新的Rectangle添加到另一个类,则为第二个类提供第一个类可以调用的addRectangle(Rectangle r)方法。在该方法中,请考虑将参数添加到作为字段的ArrayList<Rectangle>
  • 然后在检查鼠标点击时绘制矩形时遍历List。

例如:

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dialog.ModalityType;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.*;

public class AddRandomRects {

   private static void createAndShowGui() {
      JFrame frame = new JFrame("AddRandomRects");

      MainPanel mainPanel = new MainPanel();

      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);

      DialogPanelCreator dialogPanelCreator = new DialogPanelCreator(mainPanel);
      JDialog dialog = new JDialog(frame, "Create and Remove Rect Dialog", ModalityType.MODELESS);
      dialog.getContentPane().add(dialogPanelCreator.getMainComponent());
      dialog.pack();
      dialog.setLocationRelativeTo(frame);
      dialog.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

@SuppressWarnings("serial")
class MainPanel extends JPanel {
   public static final int PREF_W = 800;
   public static final int PREF_H = PREF_W;
   public static final int RECT_WIDTH = 70;
   private static final Color RECT_COLOR = Color.RED;
   private static final Color RECT_BORDER_COLOR = Color.BLUE;
   private static final Stroke RECT_BORDER_STROKE = new BasicStroke(3f);

   private List<Rectangle> rectList = new ArrayList<>();

   public MainPanel() {
      rectList.add(new Rectangle(100, 100, RECT_WIDTH, RECT_WIDTH));
   }

   public void addRectangle(int x, int y) {
      Rectangle r = new Rectangle(x, y, RECT_WIDTH, RECT_WIDTH);
      rectList.add(r);
      repaint();
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D) g.create();
      for (Rectangle rect : rectList) {
         g2.setColor(RECT_COLOR);
         g2.fill(rect);
         g2.setColor(RECT_BORDER_COLOR);
         g2.setStroke(RECT_BORDER_STROKE);
         g2.draw(rect);
      }
      g2.dispose();
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   public void removeLastRectangle() {
      if (rectList.size() > 0) {
         rectList.remove(rectList.size() - 1);
         repaint();
      }
   }
}

@SuppressWarnings("serial")
class DialogPanelCreator {
   private JPanel panel = new JPanel();
   private MainPanel mainPanel;
   private Random random = new Random();

   public DialogPanelCreator(MainPanel mainPanel) {
      this.mainPanel = mainPanel;
      panel.add(new JButton(new AddRectangleAction("Add Rectangle", KeyEvent.VK_A)));
      panel.add(new JButton(new RemoveLastRectangleAction("Remove Last Rectangle", KeyEvent.VK_R)));
   }

   public JComponent getMainComponent() {
      return panel;            
   }

   private class AddRectangleAction extends AbstractAction {
      public AddRectangleAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         int x = random.nextInt(MainPanel.PREF_W - MainPanel.RECT_WIDTH);
         int y = random.nextInt(MainPanel.PREF_H - MainPanel.RECT_WIDTH);

         mainPanel.addRectangle(x, y);
      }
   }

   private class RemoveLastRectangleAction extends AbstractAction {
      public RemoveLastRectangleAction(String name, int mnemonic) {
         super(name);
         putValue(MNEMONIC_KEY, mnemonic);
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         mainPanel.removeLastRectangle();
      }
   }

}