I'm building a game where the object is to move a knight around a world and be able to fight other knights.
I've got a class Main that starts the game:
public class Main {
public static void main(String[] args) {
new Game();
}
}
A class Game that creates a JFrame:
import java.awt.GridLayout;
import javax.swing.JFrame;
public class Game {
public Game() {
JFrame frame = new JFrame();
frame.setTitle("Knights Tournament");
frame.add(new Board());
frame.setSize(700, 700);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
And a class Board which (you guessed it!) creates the GameBoard:
public class Board extends JPanel {
Tile[][] grid = new Tile[15][15];
public Board(){
// Create the grid
CreateGrid();
// Add the player
grid[0][0] = new Player(0, 0);
}
// Method that creates a grid of tiles
private void CreateGrid() {
setLayout(new GridLayout (15, 15));
for(int i = 0; i < 15; i++){
for(int j = 0; j < 15; j++){
grid[i][j] = new Tile(i, j);
add(grid[i][j]);
}
}
}
}
The grid initialy consists of 15x15 tiles.
public class Tile extends JButton implements ActionListener {
public int xCo;
public int yCo;
public Tile(int x, int y) {
setXCo(x);
setYCo(y);
}
public void setXCo(int x) {
this.xCo = x;
}
public void setYCo(int y) {
this.yCo = y;
}
public int getXCo() {
return xCo;
}
public int getYCo() {
return yCo;
}
}
The problem i'm facing is the following: I would like to replace grid[0][0] by another class Player that expands tile. The difference between tile and player would be that the Jbutton gets a text saying 'P' i've tried this:
public class Player extends Tile{
public Player(int x, int y) {
super(x, y);
this.setText("P");
}
}
In the constructor of the class board i tried changing grid[0][0] from tile to player so it would display P, but it doesn't do so for some reason (It does change the type of grid[0][0] to player...) I hope someone can help.