Java:如何在MouseAdapter之外获取值?

huangapple 未分类评论42阅读模式
英文:

Java: How to get value outside of MouseAdapter?

问题

  1. Object[] allTabels = getTables();
  2. JButton[] buttonAry = new JButton[allTabels.length];
  3. for (int x = 0; x < buttonAry.length; x++) {
  4. buttonAry[x].setText((String) allTabels[x]);
  5. buttonAry[x].setBounds(0, 0, 125, 50);
  6. final int y = x;
  7. buttonAry[x].addMouseListener(new MouseAdapter() {
  8. @Override
  9. public void mousePressed(MouseEvent e) {
  10. displayTable(buttonAry[y].getText());
  11. }
  12. });
  13. }
英文:

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

  1. Object[] allTabels = getTables();
  2. JButton[] buttonAry = new JButton[allTabels.length];
  3. for(int x = 0; x &lt; buttonAry.length; x++) {
  4. buttonAry[x].setText((String)allTabels[x]);
  5. buttonAry[x].setBounds(0, 0, 125, 50);
  6. buttonAry[x].addMouseListener(new MouseAdapter() {
  7. @Override
  8. public void mousePressed(MouseEvent e) {
  9. displayTable(buttonAry[x].getText());
  10. }
  11. });
  12. }

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

  1. Object[] allTabels = getTables();
  2. JButton[] buttonAry = new JButton[allTabels.length];
  3. for(int x = 0; x &lt; buttonAry.length; x++) {
  4. buttonAry[x].setText((String)allTabels[x]);
  5. buttonAry[x].setBounds(0, 0, 125, 50);
  6. final int y = x;
  7. buttonAry[x].addMouseListener(new MouseAdapter() {
  8. @Override
  9. public void mousePressed(MouseEvent e) {
  10. displayTable(buttonAry[y].getText());
  11. }
  12. });
  13. }

答案1

得分: 0

  1. import java.awt.Point;
  2. import java.awt.MouseInfo;
  3. public class MouseTest
  4. {
  5. public static void main(String args[])
  6. {
  7. Point location=MouseInfo.getPointerInfo().getLocation();
  8. System.out.println(location.x);
  9. System.out.println(location.y);
  10. }
  11. }
英文:
  1. import java.awt.Point;
  2. import java.awt.MouseInfo;
  3. public class MouseTest
  4. {
  5. public static void main(String args[])
  6. {
  7. Point location=MouseInfo.getPointerInfo().getLocation();
  8. System.out.println(location.x);
  9. System.out.println(location.y);
  10. }
  11. }

huangapple
  • 本文由 发表于 2020年4月4日 18:05:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/61026501.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定