我想在 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);
我怀疑是graphics2D
为null
。我该如何解决这个问题?
最佳答案
您甚至没有正确覆盖该方法。 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/