0

I'm trying to get a value out side of a MouseAdapter. How do I do that?

Object[] allTabels = getTables();


JButton[] buttonAry = new JButton[allTabels.length];

for(int x  = 0; x < buttonAry.length; x++) {

    buttonAry[x].setText((String)allTabels[x]);
    buttonAry[x].setBounds(0, 0, 125, 50);
    buttonAry[x].addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
             displayTable(buttonAry[x].getText());
        }
    });

}

I found An answer. I just needed a final int to make it work. so I just made one.

Object[] allTabels = getTables();


JButton[] buttonAry = new JButton[allTabels.length];

for(int x  = 0; x < buttonAry.length; x++) {

    buttonAry[x].setText((String)allTabels[x]);
    buttonAry[x].setBounds(0, 0, 125, 50);
    final int y = x;
    buttonAry[x].addMouseListener(new MouseAdapter() {
        @Override
        public void mousePressed(MouseEvent e) {
             displayTable(buttonAry[y].getText());
        }
    });

}
  • 1) For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). 2) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 3) For `JButton`, add an `ActionListener` rather than `MouseListener`. – Andrew Thompson Apr 04 '20 at 10:09
  • Please check. You need to initialize the object of the JButton. You are initializing an array not the individual JButton. You could do it in multiple way. One create an interface which implements MouseAdaptor. Have a constructor which sets the value which you want to pass from here. – Allahbaksh Asadullah Apr 04 '20 at 12:28

1 Answers1

0
import java.awt.Point;
import java.awt.MouseInfo;

public class MouseTest
{
 public static void main(String args[])
 {
  Point location=MouseInfo.getPointerInfo().getLocation();
  System.out.println(location.x);
  System.out.println(location.y);
 }
}
Sync it
  • 1,180
  • 2
  • 11
  • 29