gpt4 book ai didi

java - 不知道为什么我无法让 addMouseListener(this())、addMouseMotionListener(this()) 工作

转载 作者:行者123 更新时间:2023-12-01 16:40:20 25 4
gpt4 key购买 nike

这是我的 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);
}
}

最佳答案

this 后面不需要括号。它就像一个变量名,而不是一个方法。

关于java - 不知道为什么我无法让 addMouseListener(this())、addMouseMotionListener(this()) 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4400657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com