我想向 mt JFrame 框架添加一个 mouselistener,但是当我执行 frame.addMouseListener(this) 时,我得到一个错误,我不能在静态方法中使用它
我正在制作一个检测鼠标点击然后以 int clicks 显示它的应用程序
代码
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class numberOfClicks implements MouseListener{
static int clicks = 0;
@Override
public void mouseClicked(MouseEvent e) {
clicks++;
}
static JTextField text = new JTextField();
static String string = clicks+" Clicks";
static JFrame frame = new JFrame("Click Counter");
public static void frame(){
Font f = new Font("Engravers MT", Font.BOLD, 23);
text.setEditable(false);
text.setBackground(Color.BLUE);
text.setFont(f);
text.setForeground(Color.GREEN);
text.setBorder(BorderFactory.createLineBorder(Color.BLUE));
text.setText(string);
frame.add(text, BorderLayout.SOUTH);
frame.setResizable(false);
frame.setSize(300, 300);
frame.getContentPane().setBackground(Color.BLUE);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.addMouseListener(this);
}
public static void main(String[] args){
frame();
}
@Override
public void mousePressed(MouseEvent e) {}
@Override
public void mouseEntered(MouseEvent e) {}
@Override
public void mouseExited(MouseEvent e) {}
@Override
public void mouseReleased(MouseEvent e) {}
}
最佳答案
this
不存在于静态方法中,因为静态方法是类的方法,而不是对象(this
的所有者)的方法。解决方案:从上面的代码中删除所有静态变量。除了 main 方法之外,上面的任何字段或方法都不应是静态的。
编辑
正如 Andrew Thompson 正确指出的那样,将 MouseListener 添加到 JPanel,该 JPanel 添加到 JFrame 的 contentPane。
编辑2
- 您将想要学习和使用 Java 命名约定。类名(即 NumberOfClicks)应以大写字母开头。小写字母的方法和变量名称。
- 您最好使用
mousePressed(...)
方法而不是mouseClicked(...)
,因为前者对接受按压不那么挑剔。 - 您还需要在
mousePressed(...)
方法中设置 JTextField 的文本,因为仅更改点击值不足以更改显示。 - 我尽量避免让我的 GUI(或“ View ”)类实现我的监听器。我更喜欢尽可能使用匿名内部类或独立类。
例如,
JPanel mainPanel = new JPanel();
mainPanel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
clicks++;
text.setText(clicks + " Clicks");
}
});
// add mainPanel to the JFrame...
关于java - 如何将 MouseListener 添加到框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17267109/