Reputation: 436
Maybe someone could hint me what am I doing wrong in my code? I want the player .png image to change x position whenever mouse in moved on the board, but it seems that the image does not appear at all... I am following this tutorial, but the board opens only with the black background and nothing else...
Main class:
package com.alexz;
import com.alexz.interfaces.Commons;
import javax.swing.JFrame;
import java.awt.EventQueue;
public class Main extends JFrame implements Commons{
public Main(){
initUI();
}
private void initUI(){
add(new Board());
setTitle("->>FireUP<<-");
setSize(BWIDTH, BHEIGHT);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(()->{
Main app = new Main();
app.setVisible(true);
});
}
}
Board class:
package com.alexz;
import com.alexz.interfaces.Commons;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Board extends JPanel implements Commons, Runnable{
private STATE state = STATE.IN_GAME;
private Thread animator;
private Player player;
public Board(){
initBoard();
}
private void initBoard(){
addMouseMotionListener(new MAdapter());
setFocusable(true);
setBackground(Color.BLACK);
gameInit();
setDoubleBuffered(true);
}
private void gameInit(){
player = new Player();
if(animator==null || state != STATE.IN_GAME){
animator = new Thread();
animator.start();
}
}
@Override
public void addNotify(){
super.addNotify();
gameInit();
}
private void drawPlayer(Graphics g){
if(player.isVisible()){
g.drawImage(player.getImage(), player.getX(), player.getY(), this);
}else{
state = STATE.DEAD;
player.setVisible(false);
//game over function call
}
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (state == STATE.IN_GAME){
drawPlayer(g);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
private void animationCycle(){
player.move();
}
@Override
public void run(){
long before, diff, sleep;
before = System.currentTimeMillis();
while(state == STATE.IN_GAME){
animationCycle();
diff = System.currentTimeMillis() - before;
sleep = DELAY - diff;
if (sleep < 0)
sleep = 2;
try{
Thread.sleep(sleep);
}catch(InterruptedException e){
System.out.println("ERROR: Interrupted Exception");
}
before = System.currentTimeMillis();
repaint();
}
}
private class MAdapter extends MouseAdapter{
@Override
public void mouseMoved(MouseEvent e) {
super.mouseMoved(e);
player.mouseMoved(e);
}
}
}
Upvotes: 1
Views: 65
Reputation: 5843
The condition in gameInit
is never true, as you set the state to a value it must not have before starting the Thread.
Upvotes: 3