gpt4 book ai didi

Java - GUI (swing) - 空指针异常

转载 作者:行者123 更新时间:2023-11-29 05:44:23 25 4
gpt4 key购买 nike

我有 2 个类(class):
- 第一。制作一个框架(JFrame)并在其上添加一个面板(JPanel)
- 第二个制作面板并在其上绘制一个矩形(至少我认为会)

这是头等舱

class Frame {
JFrame frame;
Panel panel;

void draw() {
frame = new JFrame ("qwertz");
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setSize(300,200);

panel = new Panel();
panel.setLayout(null);
panel.paint();
frame.add(panel);
}}

第二个

class Panel extends JPanel {
void paint() {
Graphics g = getGraphics();

g.drawRect(50,50,90,70);
}}

当我从第一个类调用 draw() 方法时,它向我抛出这个异常:

java.lang.NullPointerException  
at Panel.paint(Panel.java:8) (( g.drawRect(50,50,90,70); ))
at Frame.draw(Frame.java:15) (( panel.paint(); ))

最佳答案

那不是你应该画的。要绘制组件,请覆盖 JPanelpaintComponent(Graphics g) 方法,然后调用 repaint();

class MyPanel extends JPanel {
@Override // <-- this makes a compiler error if you typod the method name
public void paintComponent(Graphics g) {
g.drawRect(50,50,90,70);
}
}

panel = new MyPanel();
panel.setLayout(null);
panel.repaint(); // <<---- Look here! It says repaint() not paint()
frame.add(panel);

此外,如果您只需要在此面板上绘画,我会考虑使用普通的 Component,并改写 paint(Graphics g) paintComponent(Graphics g)paintComponent(Graphics g) 专用于 swing 组件。

关于Java - GUI (swing) - 空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365575/

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