How to add a MouseListener to a frame

I want to add a mouselistener to the mt JFrame frame, but when I do frame.addMouseListener (this), I get an error message that I cannot use in the static method

I am making an application that detects a mouse click and then displays it in int clicks

code

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) {} } 
+6
source share
1 answer

this does not exist in a static method, since a static method is a method of a class, not an object (owner of this ). Solution: get rid of all the statics from your code above. None of your fields or methods above should be static except the main method.


Edit
And as Andrew Thompson correctly says, add a MouseListener to the JPanel, which is added to the JPrame contentPane.


Edit 2

  • You will want to learn and use the Java naming conventions. Class names (i.e. N umberOfClicks) must begin with an uppercase letter. The names of methods and variables with a lowercase letter.
  • You better use the mousePressed(...) method rather than mouseClicked(...) , as the former is less important for accepting presses.
  • You will also want to set the JTextField text in your mousePressed(...) method, since changing the value of the clicks is not enough to change the display.
  • I try to prevent my listeners from implementing my GUI classes (or "view"). I prefer to use anonymous inner classes or autonomous classes where possible.

eg,

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

Source: https://habr.com/ru/post/947964/


All Articles