2015-11-19 57 views
0

我已經寫了這個代碼,顯示一個鼠標點擊形狀,但我有問題。當我點擊新位置時,形狀在前一個位置消失。我怎樣才能阻止發生?如何在單擊新位置時阻止形狀消失?

頭等艙:

import javax.swing.*; 
import java.awt.event.*; 
import java.awt.*; 

public class MouseClick { 
    private static int x,y; 
    private static DrawingObjects object = new DrawingObjects(); 

    public static void main(String[] args){ 

     JFrame frame = new JFrame("MouseClick"); 
     frame.setVisible(true); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(400, 400); 
     frame.add(object); 
     object.addMouseListener(new AL()); 
    } 
    static class AL extends MouseAdapter{ 
     public void mouseClicked (MouseEvent e){ 
      x = e.getX(); 
      y = e.getY(); 
      object.drawing(x, y); 
     } 
    } 
} 

二等:

import javax.swing.*; 
import java.awt.*; 

public class DrawingObjects extends JPanel{ 
    private static int x,y; 

    public void drawing(int xx, int yy){ 
     x = xx; 
     y = yy; 
     repaint(); 
    } 

    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     g.fillRect(x, y, 20, 20); 
    } 
} 
+1

您在'DrawingObjects存儲只有最後點擊位置'班。所以之前繪製的矩形會消失。 – Blip

+0

@Blip所以我應該使用數組列表? – ItssMohammed

+0

是的,你必須使用一個列表來存儲以前點擊的點 – Blip

回答

1

來處理這種情況的最好辦法是保持跟蹤每一個已經點擊點,並重繪各一paintComponent

因此改變private static int x, yprivate List<Point> points = new ArrayList<>(),並添加到該代替:

public void drawing(int x, int y){ 
    points.add(new Point(x, y)); 
    repaint(); 
} 

然後通過每個點去的時候,你重繪:

public void paintComponent(Graphics g){ 
    super.paintComponent(g); 
    for(Point p : points){ 
     g.fillRect(p.x, p.y, 20, 20); 
    } 
} 
+0

我必須改變第一課的任何東西嗎? – ItssMohammed

+0

@ItssMohammed我不認爲你應該需要,雖然我還沒有測試過。 – resueman

+0

@ItssMohammed好的,我已經測試過了,你不需要在第一堂課中改變任何東西。我沒有提到的唯一需要改變的就是進口。 'List'和'ArrayList'都在'java.util'包中。 – resueman

相關問題