简体   繁体   English

用Java绘制矩形

[英]Draw a Rectangle in Java

I want to draw a rectangle in Java on a Swing application, but I don't know how. 我想在Swing应用程序中用Java绘制一个矩形,但是我不知道如何。 I have looked at similar questions, none containing the answer I need. 我看过类似的问题,没有一个包含我需要的答案。 I have tried the following: 我尝试了以下方法:

private void paintComponent(Graphics graphics, Rectangle rect, Color color) {
    contentPane.paintComponents(graphics);
    Graphics2D graphics2D = (Graphics2D) graphics;
    graphics2D.setColor(color);
    graphics2D.draw(rect);
}

I call it like: 我这样称呼它:

contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(null);
paintComponent(contentPane.getGraphics(), new Rectangle(0, 0, 50, 50), Color.WHITE);

But it throws a NullPointerException on this line: 但它在此行上抛出NullPointerException

graphics2D.setColor(color);

I suspect it is the graphics2D being null . 我怀疑这是graphics2Dnull How can I fix this? 我怎样才能解决这个问题?

You're not even overriding the method correctly. 您甚至没有正确覆盖该方法。 paintComponent only takes a Graphics object as an argument, so you can't add your own. paintComponent仅将Graphics对象作为参数,因此您不能添加自己的对象。

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

public class Test extends JPanel {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new Test());
                frame.setVisible(true);
                frame.pack();
            }
        });
    }

    public Dimension getPreferrdSize() {
        return new Dimension(200, 200);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawRect(10, 10, 150, 40);
    }
}

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

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