Java 获取在jpanel上单击的顶点的索引
我想创建一个应用程序,显示图形并像gephi一样操作它们。 我已经编写了一些类,但是我在一个方法中遇到了一个问题。 此方法返回我单击的节点的索引。 该方法有效,但如果我更改顶点位置(移动),则无效Java 获取在jpanel上单击的顶点的索引,java,swing,graph,Java,Swing,Graph,我想创建一个应用程序,显示图形并像gephi一样操作它们。 我已经编写了一些类,但是我在一个方法中遇到了一个问题。 此方法返回我单击的节点的索引。 该方法有效,但如果我更改顶点位置(移动),则无效 //get the id of the vertices but here I have a problem, if the vertices x,y changed I can't get the id anymore. public int getIndex(){ int
//get the id of the vertices but here I have a problem, if the vertices x,y changed I can't get the id anymore.
public int getIndex(){
int i2=-1;
for(int i=0;i<Vnumber;i++)
{
if(gr.s.get(i).x==(dragged.getX()+(radius/2)) && gr.s.get(i).y==(dragged.getY()+(radius/2))){
i2=i;
break;}
else if(cnd)
if(gr.s.get(i).x==(location.getX()+(radius/2)) && gr.s.get(i).y==(location.getY()+(radius/2))){
i2=i;
break;}
}return i2;
}
}
我想你在更改顶点后忘记了更新它的位置。java不包含更新位置的方法,比如setter之类的。如果您试图通过getter从另一个类访问类变量,那么您只能获得它的值的副本,而不是实际的变量 很难说错误到底在哪里。你能举个简单的例子吗 编辑:
if(cnd){
gr.s.get(id).x=(int)location.getX()+(gr.s.get(id).radius/2);
gr.s.get(id).y=(int)location.getY()+(gr.s.get(id).radius/2);
}
你的变量名太可怕了。。。java源代码中的primary
重拨:
if(cnd){
gr.s.get(id).x=(int)location.getX()+(gr.s.get(id).radius/2);
gr.s.get(id).y=(int)location.getY()+(gr.s.get(id).radius/2);
}
如果我的想法是正确的,您可以尝试从图形中获取具有特殊id的点,但是gr.s.get(id).x返回一个按值计算的整数,您只是在副本中覆盖它的值,而不是在实际图形中。对于要更改的点,需要一个getter,然后更改x和y变量的值
顺便说一句:一门外语不能作为变量名不好的借口。这些名字可以代表任何东西。此外,我也不知道gr.s应该是什么…引用了一个完整的示例。另外,还为接口编写了代码,例如,
列表
,以防以后需要更改实现。我忘了更改图形变量(名称看起来很糟糕,因为在将代码发布到stackoverflow之前,我用法语编写了代码)因此,我的问题的解决方案是为我的类制作一些getter/setter?好的,很抱歉我会在变量名上下功夫,谢谢你的帮助!:)
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package graph;
import java.util.ArrayList;
public class Vertices
{
static int id = 0;
int x;
int y;
String str;
int radius;
Vertices()
{
int Min=200;
int Max=800;
x= Min + (int)(Math.random() * ((Max - Min) + 1));
y= Min + (int)(Math.random() * ((Max - Min) + 1));
str= "S" + (id++);
radius= 50;
}
Vertices(int w,int r)
{
int Min=20;
int Max=w-100;
x= Min + (int)(Math.random() * ((Max - Min) + 1));
y= Min + (int)(Math.random() * ((Max - Min) + 1));
str= "S" + (id++);
radius= r;
}
Vertices(int x,int y,int i)
{
this.x=x;
this.y=y;
id=i;
str="s"+id;
}
//formule random : var= Min + (int)(Math.random() * ((Max - Min) + 1));
Vertices(Vertices s)
{
x=s.x;
y= s.y;
str = s.str;
// radius = s.radius;
id=(s.id)++;
}
void Reset()
{
id=0;
}
if(cnd){
gr.s.get(id).x=(int)location.getX()+(gr.s.get(id).radius/2);
gr.s.get(id).y=(int)location.getY()+(gr.s.get(id).radius/2);
}