我想在 mt JFrame 框架中添加一个鼠标监听器,但是当我执行 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) {}
}