2014-12-27 80 views
0

这是我的代码,其输出如下图所示。 我需要在mousePressed()方法之外获得x_coor和y_coor的值。但我无法做到。我已尝试到目前为止在java中获取变量值的问题。变量的范围

  1. 声明变量Constructor

  2. 将变量声明为全局变量。

  3. 声明变量为静态。

  4. 声明变量main()

但所有没有得到我想要的。

注意:不要提及我已经知道的问题。我需要的解决方案

public class Tri_Angle extends MouseAdapter { 

    Tri_Angle(){ 
     //   int x_coor=0; 
     //   int y_coor=0; 
    } 

public static void main(String[] args) { 

    JFrame frame = new JFrame(); 

    final int FRAME_WIDTH = 500; 
    final int FRAME_HEIGHT = 500; 

    frame.setSize (FRAME_WIDTH, FRAME_HEIGHT);   
     frame.addMouseListener(new MouseAdapter() { 
     @Override 
     public void mousePressed(MouseEvent me) { 
     int x_coor= me.getX(); 
     int y_coor= me.getY(); 
     System.out.println("clicked at (" + x_coor + ", " + y_coor + ")");   
     } 

    }); 

    frame.setTitle("A Test Frame"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setVisible(true); 

//This is what i want to do, but it does not know x_coor variable here. 

      if(x_coor>=0) 
      { 
        System.out.println("clicked at (" + x_coor + ", " + y_coor + ")"); 
      }  
    } 
} 

enter image description here

回答

1

x_coor和y_coor在您定义的函数的mousePressed定义局部变量。由于它们是该功能的本地功能,因此您无法在您尝试执行的功能之外访问它们。

您可以改为将它们声明为成员变量,然后编写MouseAdapter mousePressed重写例程来更新它们。然后,您想要将一个Tri_Angle对象作为mouseListener添加到框架,而不仅仅是一个mouseListener对象。例如:

public class Tri_Angle extends MouseAdapter { 
    int x_coor, y_coor; 

    Tri_Angle() 
    { 
    x_coor = 0; 
    y_coor = 0; 
    } 

    @Override 
    public void mousePressed(MouseEvent me) 
    { 
    x_coor = me.getX(); 
    y_coor = me.getY(); 
    } 

public static void main(String[] args) 
{ 

    // code... 
    frame.addMouseListener(new Tri_Angle()); 

    // Access x_coor and y_coor as needed 

} 

也请记住,你如果(x_coor> = 0),在您的主程序声明,只是要运行1次(朝程序开始)。它不会在每次按下鼠标时都运行。如果您希望每次按下鼠标时运行某个操作,则需要使用mousePressed例程。

+0

我知道。但那就是我想要做的。那么最新的解决方案 – 2014-12-27 19:12:59

+0

我已经试过了。仍然存在问题。 – 2014-12-27 19:22:28

+0

你可以发布代码和你得到的问题吗? – Dtor 2014-12-27 19:23:05

0

声明变量的主要方法内侧和初始化

public class Tri_Angle extends MouseAdapter { 
..... 
public static void main(String[] args) { 
int x_coor =0 , y_coor=0; 
...... 
} 
..... 
} 
+0

曾试过。它不工作:) – 2014-12-27 19:53:55

+0

我试过你的程序,它为我工作... – Ashu 2015-01-05 07:21:14