user2403876
user2403876

Reputation: 339

How to pass paramters to mouse events (if possible) in Java?

Okay, so this question is probably way too basic, but I've been Googling around and haven't been able to dig up a solution (or even a workaround). My apologies in advance if some of you don't like this.

I'm creating a GUI app with a few buttons, so of course for that we need a mouse event (for when one of the buttons is clicked). So for example:

public class myProject extends JFrame implements MouseListener {
    public int x = 4;
    public static void main(String[] args) {
        Jframe app = new JFrame();
        app.setTitle // and all that jazz...        
        JLabel label = new JLabel();
        label.setText("Old text");
        app.add(label);

        // Then later on...
        public void mouseClicked(MouseEvent e) {
            app.setTitle("New Title");
            label.setText("New text");
            System.out.println(x);
            // "app" and "label" throw errors, cannot find symbol
            // But x is fine...?
        }
    }
}

I've tried making the app elements public/private instance variables, but that didn't seem to change anything. I even tried creating a sort of intermediary class to help, one that would copy references to the interactors as instance variables, and having the mouse event call methods that use those references (the second attempt was very close to the code above; but by trying to refer to set public variables from the main method gave me more errors (about how we can't call non-static objects from a static method).

So, bottom line, battling this beastly bug has been a "wild goose chase" so far, so I'd appreciate any tips/tricks/workarounds you may know of. Thanks. : )

Upvotes: 0

Views: 1895

Answers (2)

Michael Shrestha
Michael Shrestha

Reputation: 2555

try changing your code to something like this

Jframe app;
JLabel label;
    public static void main(String[] args) {
           new myProject();
        }

    public myProject()
    {
          app = new JFrame();
          app.setTitle // and all that jazz...        
          label = new JLabel();
          label.setText("Old text");
          app.add(label);
    }
      public void mouseClicked(MouseEvent e) {
          app.setTitle("New Title");
          label.setText("New text");
          System.out.println(x);
      }

Upvotes: 6

Dmitrii Bocharov
Dmitrii Bocharov

Reputation: 935

May you show the full code of the class. Now it looks like method in method. If it is an inner class, you can't get the app, label and x value if they are not final.

Upvotes: 0

Related Questions