Aby trochę nauczyć się Javy postanowiłem napisać prostą grę i natrafiłem na pewien problem.
Kiedy w klasie menu wcisnę przycisk nowa gra, w grze nie mogę się poruszać,a nawet nie mogę zamknąć okna.
Żaden listener nie reaguje.
Co mam zrobić aby po rozpoczęciu gry można było się poruszać. Poniżej część kodu aplikacji:
public class Menu extends Canvas implements ActionListener {
private static final int W = Stage.W;
private static final int H = Stage.H;
private JPanel m;
private JButton bNewGame;
private JButton bLevelEdit;
private JButton bExit;
private Tank tank;
public Menu(Tank tank) {
this.tank = tank;
m = (JPanel) tank.okno.getContentPane();
m.setPreferredSize(new Dimension(W, H));
m.setLayout(null);
bNewGame = new JButton("Nowa Gra");
bLevelEdit = new JButton("Edytor Poziomów");
JButton bScore = new JButton("201");
bExit = new JButton("Wyjście");
Font font = new Font("Comic sans ms", Font.BOLD, 16);
bNewGame.setFont(font);
bNewGame.setForeground(Color.RED);
bNewGame.setBounds(W/H, 200, 150, 100);
bLevelEdit.setBounds(200, 400, 150, 100);
bExit.setBounds(200, 500, 150, 100);
m.add(bNewGame);
m.add(bLevelEdit);
m.add(bExit);
bLevelEdit.addActionListener(this);
bExit.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
Object o = e.getSource();
if(o == bNewGame){
bNewGame.removeAll();
bLevelEdit.removeAll();
bExit.removeAll();
m.removeAll();
Game game = new Game(tank);
}
else if(o == bLevelEdit){
System.out.println("W trakcie prac");
}
else if(o == bExit){
System.exit(0);
}
}
}
package Core;
import javax.swing.JFrame;
import Game.Stage;
import Menu.Menu;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
public class Tank {
public static final int W = Stage.W;
public static final int H = Stage.H;
public JFrame okno;
public Tank(){
okno = new JFrame(".:Tank:.");
okno.setBounds(0, 0, W, H);
okno.setVisible(true);
okno.setLayout(null);
okno.addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
okno.setResizable(false);
}
public static void main(String[] args){
Tank tank = new Tank();
Menu menu = new Menu(tank);
}
}
public Game(Tank tank) {
spriteCache = new SpriteCache();
soundCache = new SoundCache();
JPanel panel = (JPanel) tank.okno.getContentPane();
setBounds(0, 0, Stage.W, Stage.H);
panel.setPreferredSize(new Dimension(Stage.W, Stage.H));
panel.setLayout(null);
panel.add(this);
panel.setVisible(true);
createBufferStrategy(2);
strategia = getBufferStrategy();
requestFocus();
addKeyListener(this);
game();
}
(...)
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit(0);
player.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
public void keyTyped(KeyEvent e) {
}