我是java的新手,我正在尝试创建一个MouseListener,以便我可以在JFrame中绘制线条。这是我的代码:
import java.awt.*;
import javax.swing.*;
import java.util.*;
public class Liner extends JComponent implements MouseListener{
static int MouseX1, MouseY1, MouseX2, MouseY2;
static JFrame window = new JFrame();
static JPanel panel = new JPanel();
public static void main(String[] args){
panel.addMouseListener(this);
window.add(panel);
window.setVisible(true);
window.pack();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g){
g.drawLine(MouseX1,MouseY1,MouseX2,MouseY2);
}
public void mousePressed(MouseEvent e) {
MouseX1 = e.getX();
MouseY1 = e.getY();
}
public void mouseReleased(MouseEvent e) {
MouseX2 = e.getX();
MouseY2 = e.getY();
}
}
我一直在犯同样的错误,包括
错误:非静态变量,无法从静态上下文引用 panel.addMouseListener(本);
和
错误:找不到符号public void mouseReleased(MouseEvent e){
(第二个引用“MouseEvent”)。