I will be making a simple game with Timer and thought how I should put everything together. I've just started with Swing and Keyboard controls. I imagine I'll have a class for the main Frame with JFrame, a class for the Board with JPanel and then I'll add all the objects to the Board, like JLabel in this example. I'll use composition to glue everything together. I'll have my methods for keyboard controls in the object classes I want to control.
How good or bad is this design and how could I improve it? Any advice would be great.
import javax.swing.JFrame;
public class Main extends JFrame {
public Board board = new Board();
public Main() {
add(board);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
setVisible(true);
}
public static void main(String args[]) {
new Main();
}
}
import javax.swing.JPanel;
public class Board extends JPanel {
public TextLabel textLabel1 = new TextLabel("Hi", "Hello", "Bye");
public TextLabel textLabel2 = new TextLabel("Bye", "GoodBye", "Farewell");
public Board() {
addKeyListener(textLabel1); //this could be a ball in my game
addKeyListener(textLabel2); //this could be something else...
add(textLabel1);
add(textLabel2);
setFocusable(true);
}
}
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JLabel;
public class TextLabel extends JLabel implements KeyListener {
private String txt1, txt2;
public TextLabel(String text, String txt1, String txt2) {
setText(text);
this.txt1 = txt1;
this.txt2 = txt2;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_A) {
setText(txt1);
}
if (key == KeyEvent.VK_L) {
setText(txt2);
}
}
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}