【问题标题】:Drawing an unknown number of shapes [closed]绘制未知数量的形状[关闭]
【发布时间】:2017-10-11 22:48:25
【问题描述】:

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

公共类绘图板{

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();

    }
}

}

【问题讨论】:

  • 如果您向我们展示您的代码,我们或许可以提供帮助。
  • “绘制无限数量的形状..” 不要将“很多”与“无限”混淆。例如,这里的屏幕是 1920 x 1080,所以如果用户点击屏幕的每个像素,app.画了一个 1 x 1 像素的“圆圈”(可以画一个点),可以绘制的最大值略高于 200 万。很多,但不是无限的。至于为每个屏幕重绘绘制成百上千个圆的问题,我不会使用这种方法,而是将每个新圆绘制到显示在JLabel 中的BufferedImage。你都尝试了些什么?你被困在哪里了?你没有问任何问题,..
  • .. 所以知道如何进一步建议是很棘手的。
  • 您能否详细说明使用“BufferdImage”的含义?我用过类似的东西。我使用了 drawImage() 方法。此外,关于“无限”这个词,将其视为我不知道我应该画多少圈的场景。
  • Could you elaborate what you mean by using 'BufferdImage'? - 详细说明是什么意思?为您提供了一个工作示例。

标签: java swing graphics2d


【解决方案1】:

查看Custom Painting Approaches

它显示了执行此操作的两种常用方法:

  1. 保留要绘制的对象的 ArrayList,然后在 paintComponent() 方法中遍历 List。

  2. 直接绘制到 BufferedImage,然后只显示 BufferedImage。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2015-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多