These are the classes I'm working on for a simple game with Java and Graphics
Main:
import javax.swing.*;
import java.awt.*;
public class FrameTest extends JFrame {
public FrameTest() {
setSize(800,600);
setVisible(true);
}
public static void main(String[] args) {
FrameTest frame = new FrameTest();
GamePanel panel = new GamePanel();
frame.add(panel);
}
}
PanelTest:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class PanelTest extends JPanel {
private PlayerTest playerRunnable;
private Thread playerThread;
public PanelTest() {
setSize(800,600);
playerRunnable = new PlayerTest();
playerThread = new Thread(playerRunnable);
//New
setLayout(new BorderLayout());
add(playerRunnable, BorderLayout.NORTH);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
setBackground(Color.red);
}
}
It just create a Panel which has a red background (I've done this to see if paintComponent() on this work, and it works in fact).
PlayerTest:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.*;
import javax.swing.JComponent;
public class PlayerTest extends JComponent implements Runnable, KeyListener {
public int x;
public int y;
private int speed;
public PlayerTest() {
speed = 10;
x = 800/2;
y = 600/4;
addKeyListener(this);
setFocusable(true);
}
public void run() {
while(true) {}
}
//New
public Dimension getPreferredSize() {
return new Dimension(30,30);
}
public void paintComponent(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(x, y, 30, 30);
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
//Spostamento a sinistra player
move(speed*-1);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
//Spostamento a destra player
move(speed);
}
if(e.getKeyCode() == KeyEvent.VK_SPACE) {
//Lancio bomba
}
}
public void move(int s) {
if (s < 0) {
if(x-s > 0) {
x += s;
System.out.println("[PLAY] move left, x: " + x);
repaint();
}
} else {
if(x+s < 800) {
x += s;
System.out.println("[PLAY] move right, x: " + x);
repaint();
}
}
}
}
Here comes the problem. This class is a Runnable (for the animation), a KeyListener (for the player movement) and a JComponent (to show the image of the player, which for now let's say it's a rectangle) I've added this component on the Panel class but it doesn't show up if I try to paint it. I don't understand why. I've benn stuck on this for so long I've finally decided to ask a question here.