[英]Java class variables are updating inconsistently between classes
一般來說,我的目標是繪制由用戶的 cursor 定義的線條。 為了實現這一點,我在一個 class 中計算出這些線條的計算,然后更新用這些新值繪制線條的 class。 總的來說,我想訪問 cursor 所在的線段列表、節點列表和當前抽象“節點”。 (節點和線段是我自己定義的類)。 繪制線條的 class 稱為 GraphicsPanel。
我在類之間設置訪問權限,如下所示:
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
}
}
雖然 lineList 和 nodeList 對象在將新 LineSegment 或 Node 添加到列表時會正確更新,但當前 Node 永遠不會更新,並且始終顯示默認值 (0, 0)。
例如,在主 class 中,我有兩個鼠標監聽器,一個用於鼠標點擊,一個用於鼠標移動。 它們有類似的功能,但是鼠標點擊監聽器同時更新當前節點和 LineSegments 的 lineList ArrayList。
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();
}
});
當我單擊 window 創建線條時,線條按預期顯示,但當前節點仍位於 (0, 0)。 我對此完全感到震驚,因為似乎只有一個變量正在更新,即使兩者都以基本相同的方式寫入更新:我修改主 class 中的 class 變量的實例,這應該修改實例GraphicsPanel class 中的變量。
感謝您對這個難題的任何幫助,並歡迎就問題所在提出建議,以及處理此應用程序的更好方法。
您不修改實例,而是創建一個new
實例,替換舊實例。 這意味着GraphicsPanel.current
將繼續指向原始實例,但MainClass.current
將指向一個新的距離。
如果你做了類似instance.setY(p.getY())
的事情,它會修改兩個類都指向的單個原始實例。
您的 MouseListener 將對象添加到 Main class 列表中。
然后它為面板參考電流分配一個不同的新 object。 但這不會改變主要的 class 參考!
您可能只是在面板代碼中沒有另一個當前引用。 只需直接分配給屬於 Main 類的當前實例!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.