Hi, I need some help, why is it my code will exit directly? it will not show the frame,can you help me please how to fix this.
Thank you in advance.
here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
public class Mygame extends JFrame{
private Image ship;
private Boolean running;
private Mypanel mypanel;
private boolean up =false;
private boolean down = false;
private boolean right =false;
private boolean left = false;
private int posX = 10;
private int posY = 100;
public Mygame(){
setTitle("Demo Game");
mypanel = new Mypanel();
getContentPane().add(mypanel);
}
class Mypanel extends JPanel {
public Mypanel(){
ship = Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/spaceship.png"));
getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP,0),
"arrowUP");
getActionMap().put("arrowUP",
arrowUP);
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT,0),
"arrowRight");
getActionMap().put("arrowRight",
arrowRight);
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT,0),
"arrowLeft");
getActionMap().put("arrowLeft",
arrowLeft);
getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN,0),
"arrowDown");
getActionMap().put("arrowDown",
arrowDown);
}
Action arrowUP = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
up=true;
repaint();
}
};
Action arrowDown = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
down = true;
repaint();
}
};
Action arrowRight = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
}
};
Action arrowLeft = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
}
};
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
if(up==true){
posX+=5;
}
if(left=true){
posY-=5;
}
}
} //End of Class Mypanel
public void addNotify(){
}
public void startGame(){
}
public void stopRun(){
running = false;
}
public void run(){
running = true;
while(running==true){
repaint();
try {
Thread.sleep(5);
}
catch(InterruptedException ex){}
}
System.exit(0);
}
public static void main(String []a){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Mygame mygame = new Mygame();
mygame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
mygame.setVisible(true);
mygame.pack();
}
});
}
}