Java类变量在类之间更新不一致
通常,我的目标是绘制由用户光标定义的线。为了实现这一点,我在一个类中计算出这些线的计算,然后用这些新值更新绘制这些线的类。总的来说,我希望访问线段列表、节点列表和光标所在的当前抽象“节点”。(节点和线段是我自己定义的类)。绘制线的类称为GraphicsPanel 我设置了类之间的访问权限,如下所示:Java类变量在类之间更新不一致,java,Java,通常,我的目标是绘制由用户光标定义的线。为了实现这一点,我在一个类中计算出这些线的计算,然后用这些新值更新绘制这些线的类。总的来说,我希望访问线段列表、节点列表和光标所在的当前抽象“节点”。(节点和线段是我自己定义的类)。绘制线的类称为GraphicsPanel 我设置了类之间的访问权限,如下所示: public class MainClass extends JFrame { protected static ArrayList<LineSegment> lineList
public class MainClass extends JFrame {
protected static ArrayList<LineSegment> lineList = new ArrayList<LineSegment>();
protected static ArrayList<Node> nodeList = new ArrayList<Node>();
protected static Node current = new Node();
// Code for calculations and user interactions
{
GraphicsPanel displayPanel = new GraphicsPanel();
// Values are updated
displayPanel.revalidate();
displayPanel.repaint();
}
}
public class GraphicsPanel extends JPanel {
private ArrayList<LineSegment> lineList = package.MainClass. lineList;
private ArrayList<Node> nodeList = package.MainClass.nodeList;
private Node current = package.MainClass.current;
public GraphicsPanel() {
}
public void paint(Graphics g) {
// Paint lines and other shapes
}
}
当我单击窗口创建线时,线将按预期显示,但当前节点仍保持在(0,0)。我对此感到非常震惊,因为似乎只有一个变量在更新,尽管这两个变量的更新方式基本相同:我在主类中修改类变量的实例,这应该修改GraphicsPanel类中变量的实例
我非常感谢您对这个难题的帮助,并欢迎您提出错误建议,以及更好地处理此应用程序的方法。您不修改实例,而是创建一个
新实例,替换旧实例。这意味着GraphicsPanel.current
将继续指向原始实例,但MainClass.current
将指向新的距离
如果您执行类似于instance.setY(p.getY())
的操作,它将修改两个类所指向的单个原始实例。您的鼠标侦听器将对象添加到主类列表中
然后将不同的新对象指定给当前面板参照。但这并没有改变主要的课堂参考
面板代码中不能有另一个当前引用。只需直接分配到属于主类的当前实例 与此无关:代码中有很多奇怪的东西。如果可能的话,找一位更有经验的Java开发人员,让他检查您的代码。避免发明自己解决问题的方法。否则,你以后将不得不放弃很多…@GhostCat我的代码中还有什么奇怪的东西?我希望有一位经验丰富的Java开发人员可以检查我的代码,但我不这样做,这就是我在这里寻求帮助的原因
displayPanel.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
current = new Node(p.getX(), p.getY());
lineList.add(new LineSegment(current, current);
// Don't worry, the line segment gets updated (correctly) with a new end node as
// the cursor moves around the window
displayPanel.revalidate();
displayPanel.repaint();
}
});