我必须制作 2 个面板,一个带有停止和启动按钮,另一个显示简笔画。当你按下开始它移动,停止它停止。当我按开始时,我收到此错误消息:Stick.actionPerformed(Stick.java:64) 线程“AWT-EventQueue-0”java.lang.NullPointerException 中的异常
即指向这一行: myBanner.startAnimation();
所以 Banner 类的 startAnimation 函数显然有问题,但我不确定。关于如何让这个东西运行的任何想法?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.BoxLayout;
public class Stick extends JFrame implements ActionListener{
public static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 500;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 200;
JButton stop, go;
Graphics g;
MovingBanner myBanner;
Thread thrd;
public static void main(String[] args){
Stick frame = new Stick();
frame.setVisible(true);
}
public Stick(){
Container contentPane;
contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(FRAME_WIDTH,FRAME_HEIGHT);
setVisible(true);
g = contentPane.getGraphics();
JPanel panel1, panel2;
panel1 = new JPanel(new FlowLayout());
panel2 = new JPanel(new FlowLayout());
contentPane.add(panel1);
contentPane.add(panel2);
stop = new JButton("STOP");
go = new JButton("GO");
stop.addActionListener(this);
go.addActionListener(this);
panel1.add(go);
panel1.add(stop);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() instanceof JButton){
JButton clickedButton = (JButton) event.getSource();
if(clickedButton == go){
myBanner.startAnimation();
thrd = new Thread (myBanner);
thrd.start();
}
if(clickedButton == stop){
myBanner.stopAnimation();
thrd = null;
}
}
}
}
class MovingBanner extends JPanel implements Runnable{
private int x;
public static final int FRAME_WIDTH = 500;
private static final int FRAME_HEIGHT = 500;
private static final int FRAME_X_ORIGIN = 150;
private static final int FRAME_Y_ORIGIN = 200;
int bodyX = 250;
int bodyY1 = 160;
int bodyY2 = 210;
int armHeight = 190;
int armLength = bodyX + 30;
int armLength1 = bodyX - 30;
int legY = 110;
private Boolean animate;
public MovingBanner(){
x = 2;
animate = true;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawLine(bodyX + x, bodyY1, bodyX + x, bodyY2); //body
g.drawOval(bodyX + x, bodyY2, 40, 40); //head
g.drawLine(armLength + x,armHeight, armLength1 + x, armHeight); //arms
g.drawLine(bodyX + x, bodyY1, bodyX + 20 + x,legY); //leg
g.drawLine(bodyX + x, bodyY1, bodyX - 20 + x, legY); //leg
}
public void run(){
while (animate){
changeX();
repaint();
try {Thread.sleep(100); } catch(Exception e){};
}
}
public void changeX() {
if (x <= FRAME_WIDTH)
x++;
else x = 2;
}
public void stopAnimation() {
animate = false;
}
public void startAnimation() {
animate = true;
}
}