java - 用Java画一个矩形

标签 java swing shapes

我想在 Swing 应用程序上用 Java 绘制一个矩形,但我不知道如何做。我看过类似的问题,但没有一个包含我需要的答案。我尝试过以下方法:

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

我这样调用它:

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

但它在这一行抛出一个NullPointerException:

graphics2D.setColor(color);

我怀疑是graphics2Dnull。我该如何解决这个问题?

最佳答案

您甚至没有正确覆盖该方法。 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);
    }
}

关于java - 用Java画一个矩形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28116694/

相关文章:

C++ 多态性问题。与 _vfptr 有关

java - 在 JDBC 中停止或终止长时间运行的查询

java - Spring 启动 hibernate : cannot delete child object separately

java - 让 SwingWorker 线程 hibernate

arrays - numpy ndarray 形状有什么作用?

python - 固定代码以制作三角形

java - 连接所有点的直线算法,没有对角线

java - Spring Boot APP部署到外部tomcat

java - JOptionPane : change the Icon

java - 窗口右侧和底部边缘的空白