簡體   English   中英

如何將MouseListener添加到框架

[英]How To Add A MouseListener To A Frame

我想在mt JFrame框架中添加一個mouselistener,但是當我執行frame.addMouseListener(this)時,我得到一個錯誤,我無法在靜態方法中使用它

我正在創建一個應用程序來檢測鼠標點擊,然后在int點擊中顯示它

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的所有者)。 解決方案:擺脫上面代碼中的所有靜態。 除主方法外,上述任何字段或方法都不應是靜態的。


編輯
正如Andrew Thompson正確指出的那樣,將MouseListener添加到添加到JFrame的contentPane的JPanel中。


編輯2

  • 您將需要學習和使用Java命名約定。 類名(即N umberOfClicks)應以大寫字母開頭。 帶小寫字母的方法和變量名稱。
  • 你最好使用mousePressed(...)方法而不是mouseClicked(...)因為前者對接受印刷機的不太貼切。
  • 您還需要在mousePressed(...)方法中設置JTextField的文本,因為僅更改單擊值不足以更改顯示。
  • 我盡量避免讓我的GUI(或“視圖”)類實現我的監聽器。 我更喜歡盡可能使用匿名內部類或獨立類。

例如,

  JPanel mainPanel = new JPanel();
  mainPanel.addMouseListener(new MouseAdapter() {
     @Override
     public void mousePressed(MouseEvent e) {
        clicks++;
        text.setText(clicks + " Clicks");
     }
  });
  // add mainPanel to the JFrame...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM