我创建了一个简单的GUI,可以在屏幕上移动3个PNG,但它无法正常工作。
以下是我拥有的代码我是GUI和swing的新手,因此可能会出现一些非常简单的常见错误,我为此向您道歉:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MovingPictures extends JPanel implements ActionListener
{
private Timer timer;
Stars star;
public MovingPictures()
{
setPreferredSize(new Dimension(800,800));
timer = new Timer(1,this);
timer.addActionListener(this);
timer.start();
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(star.getStar(),star.getStarX(),star.getStarY(),null);
g.drawImage(star.getStar2(),star.getStar2X(),star.getStar2Y(),null);
g.drawImage(star.getStar3(),star.getStar3X(),star.getStar3Y(),null);
}
public void actionPerformed(ActionEvent e)
{
star.up();
star.across();
star.diagonal();
repaint();
}
public class Stars
{
private Image stars;
private Image stars2;
private Image stars3;
private int starX;
private int starY;
private int star2X;
private int star2Y;
private int star3X;
private int star3Y;
public Stars()
{
stars = new ImageIcon("star.png").getImage();
stars2 = new ImageIcon("star2.png").getImage();
stars3 = new ImageIcon("star3.png").getImage();
starX = 0;
starY = 50;
star2X = 100;
star2Y = 0;
star3X = 0;
star3Y = 0;
}
public void up()
{
if(starY == 790)
starY = 0;
else
starY += 2;
}
public void across()
{
if(star2X == 790)
star2X = 0;
else
star2X +=2;
}
public void diagonal()
{
if (star3X == 790 )
{
star3X=0;
star3Y =0;
}
else
{
star3X += 2;
star3Y += 2;
}
}
public int getStarX()
{
return starX;
}
public int getStarY()
{
return starY;
}
public int getStar2X()
{
return star2X;
}
public int getStar2Y()
{
return star2Y;
}
public int getStar3X()
{
return star3X;
}
public int getStar3Y()
{
return star3Y;
}
public Image getStar()
{
return stars;
}
public Image getStar2()
{
return stars2;
}
public Image getStar3()
{
return stars3;
}
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setTitle(" Star Field ");
frame.setSize(new Dimension(800,800));
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
MovingPictures panel = new MovingPictures();
frame.add(panel);
panel.setBackground(Color.BLACK);
frame.setVisible(true);
}
}
我已编译并运行此程序,如果您有任何帮助,我们将不胜感激。
答案 0 :(得分:2)
请注意更改:
Stars star;
要:
Stars star = new Stars();
防止NullPointerException
在star
被实例化/创建之前被引用。{/ p>