2014-12-27 109 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