Question

So i'm writing a program that saves mouse button (currently just mousePressed, but will add mouseReleased once this will work) status to log file. How do i do that?
Current code:

import static com.sun.java.accessibility.util.AWTEventMonitor.addMouseListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class mouse {
public static void main(String[] args) throws InterruptedException{
mouse();

} 
public static void mouse() throws InterruptedException{
for(int i=0;i<10000;i++){
    addMouseListener(new MouseAdapter() { 
        public void mousePressed(MouseEvent me) { 
        writeToFile(me);    //writeToFile saves the me value to txt
        } 
       });
    TimeUnit.MILLISECONDS.sleep(1); // time delay, so it saves every 1ms
}
}


public static void writeToFile(MouseEvent me){

try{
    String data =" "+me+" ";

    File file =new File("log.txt");

    //if log.txt doesn't exist, it makes it
    if(!file.exists()){
        file.createNewFile();
    }

    //true = write
        FileWriter fileWritter = new FileWriter(file.getName(),true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        bufferWritter.write(data);
        bufferWritter.close();


    }catch(IOException e){
    }
}

}

The program compiles and runs, but it doesn't do anything.
I thank you all in advance.

Was it helpful?

Solution

If you're not trying to create a GUI and instead want to log general Mouse position, then adding a MouseListener to your class will do nothing of use. Instead understand that Java is not optimized for this type of program, and you would likely have to use JNA or JNI to trap the OS's mouse handling code. If on the other hand you wish to trap the mouse usage of a Swing GUI, then you first need to create a Swing GUI and then add your MouseListener to it. I'd advise your reading the MouseListener Tutorial for more on this.


Edit
You state:

Ultimately, it will be a part of GUI application, i'm just trying to make a concept of it.

Please understand that a MouseListener will not be functional without adding it to a Component that accepts one, that extends ultimately from the Component type, and that is displayed in a GUI. So in order to test your concept, you will again need to create a Swing GUI and add a MouseListener to one of the visualized components of your GUI. Again, please read the MouseListener tutorials.


About overwriting the file, it doesn't, i took it from my previous program, and it works properly.

Sorry, my bad -- I misread your code.


Edit 2
And as noted in comment, the listener should not have loops, but rather should respond to mouse EVENTS. For example, the following code listens for mouse press, release, and drag and displays the information in a JTextArea. It would be trivial to change this to write to file:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class SimpleMouseListenerEg extends JPanel {
   private static final int PREF_W = 600;
   private static final int PREF_H = 400;
   private JPanel listenedToPanel = new JPanel();
   private JTextArea textArea = new JTextArea(10, 25);

   public SimpleMouseListenerEg() {
      listenedToPanel.setBorder(BorderFactory.createTitledBorder("Listened To Panel"));
      MouseAdapter myMouseAdapter = new MyMouseAdapter();
      listenedToPanel.addMouseListener(myMouseAdapter);
      listenedToPanel.addMouseMotionListener(myMouseAdapter);

      textArea.setFont(new Font(Font.MONOSPACED, Font.PLAIN, 12));
      JScrollPane scrollPane = new JScrollPane(textArea);
      scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

      setLayout(new BorderLayout());
      add(listenedToPanel, BorderLayout.CENTER);
      add(scrollPane, BorderLayout.EAST);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_W, PREF_H);
   }

   // a combination MouseListener and MouseMotionListener
   private class MyMouseAdapter extends MouseAdapter {
      private String template = "%-10s [%03d, %03d]%n";

      @Override
      public void mousePressed(MouseEvent mEvt) {
         String text = String.format(template, "Pressed", mEvt.getX(), mEvt.getY());
         textArea.append(text);
      }

      @Override
      public void mouseReleased(MouseEvent mEvt) {
         String text = String.format(template, "Released", mEvt.getX(), mEvt.getY());
         textArea.append(text);
      }

      @Override
      public void mouseDragged(MouseEvent mEvt) {
         String text = String.format(template, "Dragged", mEvt.getX(), mEvt.getY());
         textArea.append(text);
      }
   }

   private static void createAndShowGui() {
      SimpleMouseListenerEg mainPanel = new SimpleMouseListenerEg();

      JFrame frame = new JFrame("SimpleMouseListenerEg");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top