我试着制作一个常规程序来显示运动图像,我不确定我做错了什么,当代码启动时,我只得到一个空程序。也许它确实在移动,但我没有把它放在可见的位置,我不确定,我会在这里发布代码。
我在netbeans工作,这可能是个问题,因为那里的一切都是预先确定的,只有真实的类,而不是我。
主要内容:
public class Main {
public static void main(String[] args) {
new MyFrame();
}
}
jframe:
public class MyFrame extends JFrame {
MyPanel panel;
public MyFrame() {
initComponents();
panel = new MyPanel();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.add(panel);
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MyFrame().setVisible(true);
}
});
}
}
jpanel:
public class MyPanel extends JPanel implements ActionListener {
final int PANEL_WIDTH = 500;
final int PANEL_HEIGHT = 500;
Image enemyRed, enemyBlue, enemyYellow, enemyPink, packMan;
Timer timer;
int xBrzina = 1;
int yBrzina = 1;
int x = 0;
int y = 0;
public MyPanel() {
initComponents();
this.setPreferredSize(new Dimension(PANEL_WIDTH, PANEL_HEIGHT));
enemyRed = new ImageIcon("C:\\Users\\SMRTNIK\\Documents\\enemy.png").getImage();
timer = new Timer(100, null);
}
public void paint(Graphics g) {
Graphics2D G2D = (Graphics2D) g;
G2D.drawImage(enemyRed, x, y, null);
super.paint(g);
}
@Override
public void actionPerformed(ActionEvent e) {
if (x >= PANEL_WIDTH - enemyRed.getWidth(null) || x < 0) {
xBrzina = xBrzina * -1;
}
x = x + xBrzina;
if (y >= PANEL_WIDTH - enemyRed.getWidth(null) || y < 0) {
yBrzina = yBrzina * -1;
}
repaint();
}
}
1条答案
按热度按时间aurhwmvo1#
也许可以创建新的普通类并插入代码,但不要插入那些预定义的元素。