This is my tile class:
public class Tile extends JLabel {
public static Font font = new Font("Serif", Font.BOLD, 39);
private static char _c;
public Tile(char c, Color background) {
setBackground(background);
setOpaque(true);
_c = c;
setText(convert());
setFont(font);
}
public static char randomLetter() {
Random r = new Random();
char randomChar = (char) (97 + r.nextInt(26));
return randomChar;
}
public static Color randomColor() {
Random rand = new Random();
float r = rand.nextFloat();
float g = rand.nextFloat();
float b = rand.nextFloat();
Color randomColor = new Color(r, g, b);
return randomColor;
}
public static char getChar() {
return _c;
}
public String convert() {
return String.valueOf(getChar());
}
}
my GUI class
public class Game implements KeyListener {
public static Game game;
private Model model;
public Game() {
model = new Model();
for (int i = 0; i < 4; i++) {
model.add(new Tile(Tile.randomLetter(), Tile.randomColor()));
}
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new GridLayout(4, 1));
frame.setSize(500, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
for (Tile tile : model.getTiles()) {
frame.add(tile);
}
frame.getContentPane().addKeyListener(this);
frame.getContentPane().setFocusable(true);
frame.getContentPane().requestFocusInWindow();
}
@Override
public void keyPressed(KeyEvent arg0) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
if (model.getTiles(0).Tile.getChar == e.getKeyChar()) {
System.out.println("YOU REMOVED A TILE!!!");
}
// model.removeByChar(e.getKeyChar());
}
public static void main(String[] args) {
new Game();
}
}
and my model class
public class Model {
private ArrayList<Tile> list = new ArrayList<Tile>();
public Model() {
}
public void add(Tile tile) {
list.add(tile);
}
public ArrayList<Tile> getTiles() {
return list;
}
}
I'm trying to remove a tile when a key is pressed relative to the tile's letter, but I don't know how to make that happen.
@Override
public void keyTyped(KeyEvent e) {
for (Tile t : model.getTiles()) {
if (t.getChar() == e.getKeyChar()) {
System.out.println("YOU REMOVED A TILE!!!");
frame.remove(t);
frame.repaint();
}
}
// model.removeByChar(e.getKeyChar());
}