繁体   English   中英

使用Swing在Java中绘制多个矩形

[英]Drawing multiple rectangles in Java using Swing

我有代码

import java.awt.*;
import javax.swing.*;

public class MondrianPanel extends JPanel
{
    public MondrianPanel()
    {
        setPreferredSize(new Dimension(200, 600));
    }

    public void paintComponent(Graphics g) {
        for(int i = 0; i < 20; i++) {
            paint(g);
        }
    }

    public void paint(Graphics g)
    {
        Color c = new Color((int)Math.random()*255, (int)Math.random()*255, (int)Math.random()*255);
        g.setColor(c);
        g.fillRect((int)Math.random()*200, (int)Math.random()*600, (int)Math.random()*40, (int)Math.random()*40);
    }

}

我想要做的是在屏幕上随机的位置绘制一堆颜色随机的矩形。 但是,当我运行它时,我只会看到一个灰色框。 我在读这个问题, 用Java Swing画了多行,我看到您应该有一个单独的paintComponent来调用很多次绘画,因此我尝试将我的代码进行适应,但是仍然无法正常工作。

这里最大的问题是(int) Math.random() * something始终为0 这是因为强制类型转换首先执行,然后为0 ,然后再乘以0

它应该是这样的: (int) (Math.random() * something)

然后,应将paint(Graphics g)重命名为draw(Graphics g) ,否则将以错误的方式覆盖paint

以下代码根据需要工作:

public class TestPanel extends JPanel {
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (int i = 0; i < 20; i++) {
            draw(g);
        }
    }

    public void draw(Graphics g) {
        Color c = new Color((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255));
        g.setColor(c);
        g.fillRect((int) (Math.random() * 400), (int) (Math.random() * 300), (int) (Math.random() * 40), (int) (Math.random() * 40));
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.getContentPane().add(new TestPanel(), BorderLayout.CENTER);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(400, 300);
        f.setVisible(true);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM