我正在学习Java中的GUI。这是我的自定义JFrame:
package ui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import management.GameManager;
@SuppressWarnings("serial")
public class TaylorIsHungryGUI extends JFrame {
private GameManager gameMgr;
private GamePanel gp;
public TaylorIsHungryGUI() {
gameMgr = new GameManager("taylor_head.jpg", "sushi.jpg");
setUpGUI();
}
private void setUpGUI() {
setTitle("Taylor is Hungry");
setSize(1000, 750);
setLayout(new GridBagLayout());
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gp = new GamePanel(gameMgr);
gp.setPreferredSize(new Dimension(800, 650));// hardCoded sizing
gp.setMaximumSize(new Dimension(800, 650)); // hardCoded sizing
gp.setMinimumSize(new Dimension(800, 650)); // hardCoded sizing
gp.setBackground(Color.GRAY);
gp.requestFocus();
addListeners();
add(gp);
setVisible(true);
}
private void addListeners() {
gp.addKeyListener( new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_RIGHT) {
gameMgr.getPlayer().setX(gameMgr.getPlayer().getX() + 100);
gp.repaint();
gp.revalidate();
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
});
}
public static void main(String[] args) {
new TaylorIsHungryGUI();
}
}
这是我的自定义面板:
package ui;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;
import management.GameManager;
@SuppressWarnings("serial")
public class GamePanel extends JPanel {
private GameManager gameMgr;
public GamePanel(GameManager gameMgr) {
super();
this.gameMgr = gameMgr;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(gameMgr.getPlayer().getFace(), gameMgr.getPlayer().getX(), 500, this);
}
}
问题:当我按下KeyPressed事件的键时,我的GamePanel中的图像不会移动。 为什么是这样?以下是其他一些注意事项:
另外,让我知道您对我如何组织代码的想法(如在自定义JFrame和JPanel中),以及您是否知道采用不同的方法来处理它。