所以这是我的RocketShip的面板,我想将MouseListener和我的MouseMotionListener添加到它,但它告诉我“这个”是一个无效的名称。我的教科书有时使用这个,教授也建议我们在这个例子中使用“this”,所以我不知道问题是什么。我的代码如下。感谢您提供的任何建议。
import java.applet.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
//I cannot understand how to draw my new rocketship or how to update the coordinates for mouse moved, mouse dragged, mouse pressed or mouse released
//also not sure how to work with setShooting
public class RocketShipPanel extends JPanel implements MouseListener,MouseMotionListener
{
private final int WIDTH = 300, HEIGHT = 300;
RocketShip ship = new RocketShip();
public RocketShipPanel(){ //constructor
addMouseListener (this());
addMouseMotionListener (this());
setBackground (Color.black);
setPreferredSize (new Dimension(WIDTH, HEIGHT));
}
public void paintComponent (Graphics page)
{
super.paintComponent(page);
ship.draw(page, 50);
}
public void mousePressed (MouseEvent event)
{
ship.setShooting(true);
repaint();
}
public void mouseReleased (MouseEvent event)
{
ship.setShooting(false);
repaint();
}
public void mouseMoved (MouseEvent event)
{
Point point1 = event.getPoint();
int x = point1.x;
int y = point1.y;
ship.move(x, y);
repaint();
}
public void mouseDragged (MouseEvent event)
{
Point point1 = event.getPoint();
int x = point1.x;
int y = point1.y;
ship.move(x, y);
//pointList.add(event.getPoint());
repaint();
}
//--------------------------------------------------------------
// Provide empty definitions for unused event methods.
//--------------------------------------------------------------
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseClicked(MouseEvent event) {}
public static void main (String[] args)
{
JFrame frame = new JFrame ("RocketShip");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new RocketShipPanel());
frame.pack();
frame.setVisible(true);
}
}
答案 0 :(得分:6)
this
后您不需要括号。它就像一个变量名,而不是一个方法。
答案 1 :(得分:0)
这是JAVA中的关键字,不应将其视为方法,它是对当前对象的引用。您可以通过以下链接了解此关键字 - http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html