2014-05-17 56 views
0

我是很新的顯卡,擁有Java,所以只問是否需要任何額外的信息:)使用重繪()

我想根據點擊鼠標在哪裏畫的形狀與參數調用的paintComponent()屏幕。因此,我需要將點擊的位置的x和y座標傳遞給paintComponent()方法,以便它知道在哪裏繪製形狀。

public void mouseClicked(MouseEvent e) { 
    System.out.println("Adding Shape"); 
    repaint(); 
} 

class CanvasDrawArea extends JPanel{ 
    //this should run when the program first starts 
    @Override 
    public void paintComponent(Graphics g){ 
     super.paintComponent(g); 
     canvas.setBackground(CANVAS_COLOR); 
    } 

    //here is where the question is 
    public void paintComponent(Graphics g, int x, int y){ 
     super.paintComponent(g); 
     g.fillRect(x, y, RECTANGLE_WIDTH, RECTANGLE_HEIGHT); 
    } 
} 

基本上我試圖通過使一個超負荷的paintComponent運行正確的程序通過調用repaint()/pack()方法開始時,和一個當我給它的X和Y座標將運行。然而,我不確定我應該如何去傳遞x和y參數,因爲在repaint()方法中沒有辦法通過它們。

回答

3
  1. 你永遠不應該有需要調用paintComponentpaint這些直接在需要時被重繪管理器自動調用...
  2. 創建java.util.List並存儲在它的每個鼠標點擊的Point,從調用repaint完成此操作後,方法爲mouseClicked
  3. 在您的paintComponent(Graphics)方法中,遍歷點的List並繪製所需的形狀。

舉一個簡單的例子...

Dotty

import java.awt.Color; 
import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Point; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.util.ArrayList; 
import java.util.List; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.UIManager; 
import javax.swing.UnsupportedLookAndFeelException; 

public class Dotty { 

    public static void main(String[] args) { 
     new Dotty(); 
    } 

    public Dotty() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
        ex.printStackTrace(); 
       } 

       JFrame frame = new JFrame("Testing"); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.add(new DottyPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class DottyPane extends JPanel { 

     private List<Point> points; 

     public DottyPane() { 
      points = new ArrayList<>(25); 
      addMouseListener(new MouseAdapter() { 

       @Override 
       public void mouseClicked(MouseEvent e) { 
        points.add(e.getPoint()); 
        repaint(); 
       } 

      }); 
     } 

     @Override 
     public Dimension getPreferredSize() { 
      return new Dimension(200, 200); 
     } 

     @Override 
     protected void paintComponent(Graphics g) { 
      super.paintComponent(g); 
      Graphics2D g2d = (Graphics2D) g.create(); 
      g2d.setColor(Color.RED); 
      for (Point p : points) { 
       g2d.fillOval(p.x - 5, p.y - 5, 10, 10); 
      } 
      g2d.dispose(); 
     } 

    } 

} 
+0

謝謝!沒有意識到我應該只使用一個類變量... – TwoShorts