绘制未知数量的形状

时间:2017-05-12 14:54:28

标签: java swing graphics2d

该程序应该在用户点击的位置绘制圆圈。目前,它只画了5个圆圈。我想知道,如何修改这段代码,以便它可以无限制地绘制圆圈。考虑一个我不知道应该绘制的圆圈数量的场景。这是我的代码:

公共类DrawingBoard {

public static void main(String[] args){

    new LookAndFeel();

}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

}

类LookAndFeel扩展了JPanel {

JFrame f;
int n = 0;
double points[][] = new double[6][5];
EventManager EMobj = new EventManager();

public LookAndFeel(){
    f = new JFrame("Drawing Board");
    f.setBounds(0,0,1920,1080);
    f.add(this);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    f.setResizable(false);
    addMouseListener(EMobj);

}

public void paintComponent(Graphics g){

    g.setColor(Color.RED);

    if(n >= 1)
        g.fillOval((int)points[0][0], (int)points[1][0], 80, 80);
    if(n >= 2)
        g.fillOval((int)points[1][1], (int)points[2][1], 80, 80);
    if(n >= 3)
        g.fillOval((int)points[2][2], (int)points[3][2], 80, 80);
    if(n >= 4)
        g.fillOval((int)points[3][3], (int)points[4][3], 80, 80);
    if(n >= 5)
        g.fillOval((int)points[4][4], (int)points[5][4], 80, 80);       
    if(n==5)
        removeMouseListener(EMobj);
}

class EventManager extends MouseAdapter{


    public void mouseClicked(MouseEvent e){

        points[n][n] = e.getX();
        points[n+1][n] = e.getY();
        n++;
        repaint();

    }
}

}

0 个答案:

没有答案