Estou a fazer um projecto do jogo Sokoban, e cheguei á parte em que criei 2 JButtons para selecionar o nivel. Agora quando tento correr uma programa da um erro. Eu criei ambos os botoes e a açao numa class Buttons e chamei-a essa class noutra class que dá start ao programa. Usei o seguinte para os botoes:
public class Buttons extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
public Buttons(){
this.getContentPane().setLayout(new FlowLayout());
JButton lvl1btn = new JButton("Level 1");
JButton lvl2btn = new JButton("Level 2");
lvl1btn.setBounds(700,0,100,25);
lvl1btn.setBounds(800,0,100,25);
lvl1btn.addActionListener(this);
lvl2btn.addActionListener(this);
lvl1btn.setActionCommand("Level 1");
lvl2btn.setActionCommand("Level 2");
}
@Override
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if(action.equals("Level 1")){
Board board = new Board();
board.createWorldOne();
}else if(action.equals("Level 2")){
Board board = new Board();
board.createWorldTwo();
}
}
E chamei assim:
public final class SokobanStart extends JFrame {
public SokobanStart() {
InitUI();
}
public void InitUI() {
Board board = new Board();
Buttons buttons = new Buttons();
add(board,buttons);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(board.getBoardWidth(),board.getBoardHeight());
setLocationRelativeTo(null);
setTitle("Sokoban Game!");
}
public static void main(String[] args) {
SokobanStart sokobanStart = new SokobanStart();
sokobanStart.setVisible(true);
}
}
E deume a seguinte thread:
Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null) at java.desktop/java.awt.BorderLayout.addLayoutComponent(BorderLayout.java:431) at java.desktop/javax.swing.JRootPane$1.addLayoutComponent(JRootPane.java:507) at java.desktop/java.awt.Container.addImpl(Container.java:1148) at java.desktop/java.awt.Container.add(Container.java:1025) at java.desktop/javax.swing.JFrame.addImpl(JFrame.java:553) at java.desktop/java.awt.Container.add(Container.java:993) at Sokoban.SokobanStart.InitUI(SokobanStart.java:16) at Sokoban.SokobanStart.(SokobanStart.java:10) at Sokoban.SokobanStart.main(SokobanStart.java:25)