2014-09-19 41 views
0

我创建了一个Arraylist对象(圆形)。我添加了一个mouseclick事件,所以一旦我点击面板,一个圆圈将被淹死并存储在数组列表中。我被卡住了,想不到我的代码有什么方法......我希望能够帮助我解决问题的一些提示。向Arraylist中添加一个绘制的圆对象

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


public class Circle extends JFrame 
{ 

    private JPanel panel; 
    private ArrayList <Circle> circle; 

    public static void main(String[]args) 

     { 

     setTitle("Drawing Circles"); 
     // Set the size of the window. 
     setSize(WINDOW_WIDTH, WINDOW_HEIGHT); 
     // Specify an action for the close button. 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     // set the Frame's layout 
     setLayout(new BorderLayout()); 
     // Add the panels to the frame's content pane. 
     add(panel, BorderLayout.CENTER); 
     // Display the window. 
     setVisible(true); 

     circle = new ArrayList<Circle>(); 
     } 

    public Circle() 
     { 
     panel.addMouseListener(new ClickingLitener()); 
     } 




    private class ClickingLitener implements MouseListener 
    { 

     public void mouseClicked(MouseEvent e) 
      { 
      circle.add(new Circle()); 

      // somehow I need to call panel.paintComponent ... right ? 
      } 
    } 

} 
+0

第一件事是将“新的Circle()”赋值给一个局部变量。做你想做的一切,包括油漆等,然后添加本地圈子到收藏。 – 2014-09-19 02:02:24

回答

1

您的Circle类扩展了JFrame。您无法在JPanel上添加或绘制JFrame,因此您的基本方法存在缺陷。

如果您想要自定义绘画以在面板上绘制Circle,则需要存储有关要绘制的Circle的信息。然后在面板的paintComponent()方法中遍历ArrayList并绘制所有圆。当您向ArrayList添加新的Circle时,只需在面板上调用repaint()。

检查出Custom Painting Approaches为这种方法的工作示例。该代码在面板中添加了“矩形”,但您应该可以轻松更改代码以添加圆圈。