I am trying to build a small monopoly game. Here you can see the part of the code that I am having trouble with.
public class Board extends JPanel {
private ImageIcon image;
private JLabel label;
static Player p1;
static Player p2;
public Board() {
p1 = new Player("Jack", 1);
p2 = new Player("Matt", 2);
setLayout(null);
image = new ImageIcon("board.jpg");
label = new JLabel(new ImageIcon("/Users/Onurcan/Documents/"
+ "workspace/Monopoly/src/board.jpg"));
add(p1.getToken());
add(label);
}
public class Monopoly {
public Monopoly() {
JFrame frame = new JFrame("Monopoly");
frame.setSize(1378, 900);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new Board(), BorderLayout.WEST);
frame.setVisible(true);
}
}
As you can guess I create a new Monopoly object in my test class to run this program. When I remove the setLayout(null) I can see both token and board in program. But without typing setLayout(null) I cannot move my token to starting point. While creating player if second parameter is 1 that means token is a hat, if second parameter is 2 it means it is a shoe. So I am asking that how can I do not lose visual with setLayout(null)? Or withouy setting layout to null how can I change my tokens position?
So I am asking that how can I do not lose visual with
setLayout(null)
?
Start by taking a look at Laying Out Components Within a Container. The layout management API is responsible for making decisions about how big components should be and where they should be located, based on their implementation.
Once you remove this, your component doesn't know how it should be sized or positioned. In fact, by default it's 0x0x0x0.
Layout management is a fundamental aspect of the Swing API
without setting layout to
null
how can I change my tokens position?
Well, the short answer is to call setBounds
on the components and give them a size and position. This approach can be troublesome at best, because the layout management API is so central to the whole Swing API
The longer answer, and the one I would prefer, would be to write a layout manager which could make the decisions for you. Knowing where each player is on the board and how best to place the pieces on the board based on it's configuration