[英]MongoTimeoutException with Java. No changes before getting the issue
[英]Issue with getting Variables values in java. Scope of Variable
这是我的代码,输出如下图所示。 我需要在mousePressed()
方法之外获取x_coor和y_coor的值。 但是我做不到。 到目前为止我已经尝试过
在Constructor
声明变量。
将变量声明为全局变量。
将变量声明为静态。
在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.