java - 不显示要移动到 JFrame 的图像
问题描述
我试图制作一个常规程序来显示运动图像,我不确定我做错了什么,当代码启动时我只得到一个空程序。也许它实际上在移动,但我没有让它可见,我不确定,我会在这里发布代码。
我在 NetBeans 工作,这可能是个问题,因为那里的一切都必须预先确定,并且只是真实的类,而不是我。
主要的:
public class Main {
public static void main(String[] args) {
new MyFrame();
}
}
框架:
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);
}
});
}
}
面板:
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();
}
}
解决方案
也许创建新的普通类并插入该代码,但不要插入那些预定义的元素。
推荐阅读
- reactjs - Bitbucket 管道反应到 Ubuntu 服务器
- phpspreadsheet - PhpSpreadsheets - 如何按列和行获取单元格坐标?
- c++ - 类的隐式转换
- python - 从 POST 请求中解析嵌套的 Url 编码数据
- python - 按照数字海洋教程使用 nginx gunicorn 将烧瓶应用程序部署到 ubbuntu 18.04 时遇到问题
- oracle - 在存储过程中选择
- typescript - 如何从将对象的属性名称作为参数的函数指定返回值的类型为 object.propertyName 的类型
- object - Delphi 中的可选参数
- reactjs - 如何在反应钩子中停止useEffect内存泄漏
- javascript - 在片段着色器中包裹图像时出现奇怪的线条