【发布时间】:2021-09-15 10:21:36
【问题描述】:
我尝试制作一个常规程序来显示运动图像,我不确定我做错了什么,当代码启动时我只得到一个空程序。也许它实际上在移动,但我没有让它可见,我不确定,我会在这里发布代码。
我在 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();
}
}
【问题讨论】:
-
enemyRed = new ImageIcon("C:\\Users\\SMRTNIK\\Documents\\enemy.png").getImage();应用程序资源将在部署时成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。
标签: java image swing graphics 2d