2013-04-11 72 views
1

計劃奇重繪功能

傢伙

嗨的簡要說明。今天早上我很無聊,決定寫一個圖表程序。最終,我將能夠在此軟件上運行諸如Dijksta的算法

當屏幕上發生任何變化時,請致電repaint方法JPanel,其中所有東西都塗上了。這是JPanel paint方法:

public void paint(Graphics g) 
{ 
    for(Node node : graph.getNodes()){ 
     node.paint(g); 
    } 

    for(Link link : graph.getLinks()){ 
     link.paint(g); 
    } 
} 

它簡單地通過在列表中的每個元素的週期,和油漆他們。

爲節點類的paint方法是:

public void paint(Graphics g) 
{ 
    g.setColor(color); 
    g.drawOval(location.x, location.y, 50, 50); 
    g.setColor(Color.BLACK); 
    g.drawString(name, location.x + 20, location.y + 20); 
} 

而對於鏈接是:

public void paint(Graphics g) 
{ 
    Point p1 = node1.getLocation(); 
    Point p2 = node2.getLocation(); 
    // Grab the two nodes from the link. 
    g.drawLine(p1.x + 20, p1.y + 20, p2.x + 20, p2.y + 20); 
    // Draw the line between them. 
    int midPointX = ((p1.x + p2.x)/2) + (100/(p2.x - p1.x)); 
    int midPointY = ((p1.y + p2.y)/2) + 30; 
    // Compute the mid point of the line and get it closer to the line. 
    g.setColor(Color.BLACK); 
    g.drawString(String.valueOf(weight), midPointX, midPointY); 
} 

的問題

我遇到的問題出現時,我使用JOptionPane類。當我選擇添加新節點的選項並選擇放置位置時,彈出一個inputDialog,詢問節點的名稱。

的節點被添加細,對於出現這種情況:

enter image description here 這是一個常見的問題;也許是paintrepaint的問題?

儘管如此,這裏是調用inputDialog代碼:

Function addNode = functionFac.getInstance(state); 
       String name = ""; 
       while(!name.matches("[A-Za-z]+")) { 
        name = JOptionPane.showInputDialog("Please enter the name of the node.", null); 
       } 

       addNode.execute(stage, new NodeMessage(arg0.getPoint(), name)); 

PS:功能是我寫的接口類型。 「

+0

+1用於全面檢查常見問題的不常見問題。 – trashgod 2013-04-11 17:25:07

回答

4

」Swing程序應該覆蓋paintComponent()而不是覆蓋paint()。「 - Painting in AWT and Swing: The Paint Methods

「如果不遵守不透明屬性,您可能會看到的視覺假象。」 - JComponent

參見本Q&A是考察一個相關的問題。

+1

啊優秀!我只是將'paint'重新命名爲'paintComponent',並將其命名爲'super.paintComponent',並將其完全移除。很好的答案,謝謝你的鏈接:) +1! – christopher 2013-04-11 17:22:01

+0

另外,Graphics上下文在繪製過程中被共享,因此您可能會在繪圖中保留以前繪製的組件。其中一個paintComponent所做的工作是準備組件繪畫 – MadProgrammer 2013-04-11 19:01:03

+0

作爲參考,@MadProgrammer使用術語[「paint chain」]解決了類似的異常(http://stackoverflow.com/search?q=user%3A992484+%22paint+鏈%22)。 – trashgod 2013-04-11 19:51:48