gpt4 book ai didi

Java swing 绘图图形空指针?

转载 作者:行者123 更新时间:2023-11-29 06:35:56 25 4
gpt4 key购买 nike

我想在我的 JFrame 窗口中绘制一个矩形,但我总是遇到 nullpointer 错误。为什么会这样?绘制矩形、渐变等图形或 Swing 飘落的雪花之类图形的最佳(正确)方法是什么?

这是异常(exception):

Exception in thread "Thread-0" java.lang.NullPointerException
at gui.Window.run(Window.java:24)
at gui.Window$1.run(Window.java:34)
at java.lang.Thread.run(Unknown Source)

来源:

public class Window extends JFrame implements Runnable {

private boolean run = true;

public Window() {
super.setSize(500, 500);
super.setTitle("MY GUI");
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
super.setContentPane(new Container());
}

@Override
public void run() {
Graphics g = super.getContentPane().getGraphics();
while (this.run) {
g.setColor(new Color(0, 0, 0, 255));
g.fillRect(0, 0, 200, 200);
}
}

public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
Window window = new Window();
window.run();
}
}).start();
}
}

Error line 24: g.setColor(new Color(0, 0, 0, 255));

为什么要这样做?

最佳答案

您发布的代码毫无意义。

首先,与 Swing 组件的每次交互(调用 repaint() 除外)都必须在事件派发线程中完成。

其次,运行一个不断在 Graphics 上绘制相同内容的无限循环是没有意义的。

第三,事情不是这样的。您无法获取与组件关联的图形并在其上绘制。相反,您必须覆盖 Swing 组件的 paintComponent(Graphics) 方法,等待 swing 调用此方法,然后使用提供的 Graphics 参数来绘制您想要的任何内容。如果您想更改正在绘制的内容,则需要对该元素调用 repaint()。不要用 JFrame 这样做。创建JComponent 或JPanel 的子类,并将该子类的实例添加到一个JFrame 中,然后使这个JFrame 可见:

public class CustomComponent extends JComponent {
@Override
public void paintComponent(Graphics g) {
// paint here
}

@Override
public Dimension getPreferredSize() {
// return preferred size here
}

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

关于Java swing 绘图图形空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20709120/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com