2014-05-17 88 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