I'm doing a Sokoban game project, and got to the point where I created 2 JButtons to select the level. Now when I try to run a program a mistake. I created both the buttons and the action in a class Buttons and called it this class in another class that gives start to the program. I used the following for the buttons:
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();
}
}
And I called it:
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);
}
}
And get the following thread:
Exception in thread "main" java.lang.IllegalArgumentException: can not 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)