画面上で画像を移動するタイマーの速度または遅延を制御できるようにしたいJTextField
. NullPointerException
私は行でCarAnimationPanel
ある行61を取得していtimer.start()
ます。
これは私のコードです...
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
public class Exercise18_17 extends JApplet {
private static JTextField jtfCar1;
private int num1;
public Exercise18_17(){
URL imageURL = this.getClass().getResource("images/TN_buick 1912small.GIF");
Image image = new ImageIcon(imageURL).getImage();
setLayout(new GridLayout(5,4,2,2));
add(new CarAnimationPanel(image));
}//endo of 15_15 constructor
public static class CarAnimationPanel extends JPanel implements ActionListener {
private Image image;
private int delay ;
private int num1 = 0;
private Timer timer;
int x = 0;
int y = 20;
public CarAnimationPanel(Image image) {
add(jtfCar1 = new JTextField(5));
jtfCar1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
num1 = Integer.parseInt(jtfCar1.getText().trim());
if (e.getSource() == jtfCar1){
delay = num1;
timer = new Timer(delay, this);
}
}
});
timer.start();
this.image = image;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
if (x > getWidth()) {
x -= 20;
}
x += 5;
g.drawImage(image, x, y, this);
}
public void actionPerformed(ActionEvent e) {
repaint();
}
}
public static void main(String[] args) {
// Create a frame
JFrame frame = new JFrame("Exercise18_17");
// Create an instance of the applet
JApplet applet = new Exercise18_17();
// Add the applet to the frame
frame.add(applet, BorderLayout.CENTER);
// Invoke applet's init method
applet.init();
// Display the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}