1

I am pretty new to java, and I am trying to make a MouseListener so that I can draw lines in a JFrame. Here is my code:

import java.awt.*;
import javax.swing.*;
import java.util.*;

public class Liner extends JComponent implements MouseListener{

static int MouseX1, MouseY1, MouseX2, MouseY2;
static JFrame window = new JFrame();
static JPanel panel = new JPanel();

public static void main(String[] args){
    panel.addMouseListener(this);
    window.add(panel);
    window.setVisible(true);
    window.pack();
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public void paint(Graphics g){
    g.drawLine(MouseX1,MouseY1,MouseX2,MouseY2);
}


public void mousePressed(MouseEvent e) {
    MouseX1 = e.getX();
    MouseY1 = e.getY();
}
public void mouseReleased(MouseEvent e) {
    MouseX2 = e.getX();
    MouseY2 = e.getY();
}    
} 

I have been getting the same errors a lot, including

error: non-static variable this cannot be referenced from a static context panel.addMouseListener(this);

and

error: cannot find symbol public void mouseReleased(MouseEvent e) {

(the second one refers to "MouseEvent").

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
Tdonut
  • 153
  • 5
  • `this` doesn't exist within a `static` context, `this` refers to the current instance of an object, but since you're in a `static` context, no object exists – MadProgrammer Nov 12 '15 at 23:56
  • For the second error you should `import java.awt.event.*` which contains `MouseEvent` class. For the first error you can't refer this in a static method, probably you meant `panel.addMouseListener(new Liner())`. – Jack Nov 12 '15 at 23:58
  • As to your second problem, add `import java.awt.event.*` to your imports. A `import` statement is not recursive, it only imports the classes from the specified package (when used with a wild card) – MadProgrammer Nov 12 '15 at 23:58
  • @Jack That last part (*`panel.addMouseListener(new Liner())`*) is actually misleading, as then the OP's paint code won't work. May they should actually make `panel` and instance of `Liner` and register the `MouseListener` within it's constructor instead? – MadProgrammer Nov 12 '15 at 23:59
  • When performing custom painting in Swing, it is generally encouraged to override `paintComponent` instead of `paint`. It's also (highly) recommended that you call the paint methods `super` method, in order to maintain the integrity of the painting process. See [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) and [Performing Custom Painting](http://docs.oracle.com/javase/tutorial/uiswing/painting/) for more details – MadProgrammer Nov 13 '15 at 00:01
  • @MadProgrammer: that was exactly what I was answering but the question has been closed before I ended the answer so I had to shorten it to a comment. – Jack Nov 13 '15 at 00:03
  • @Jack Unfortunately it's not what your comment said :P – MadProgrammer Nov 13 '15 at 00:23

0 Answers0