簡體   English   中英

在Java中獲取變量值的問題。 變量范圍

[英]Issue with getting Variables values in java. Scope of Variable

這是我的代碼,輸出如下圖所示。 我需要在mousePressed()方法之外獲取x_coor和y_coor的值。 但是我做不到。 到目前為止我已經嘗試過

  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 + ")");
           }       
    }
 }

在此處輸入圖片說明

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

}

還請記住,您的主例程中的if(x_coor> = 0)語句僅將運行1次(朝程序的開頭)。 它不會在每次按下鼠標時運行。 如果您希望每次按下鼠標時都可以運行某項,則該操作必須在mousePressed例程中。

在main方法中聲明變量並初始化

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM