I have a MapPanel class which extends JPanel. I display some objects in this grid and I want some of them to be linked by a line. So I am trying to draw this lines into MapPanel.paintComponent but I no line has been shown. I check the line parameters (x1,y1,x2,y2) by System.out.println() and they are right ( kind of 0 < param < 600, measures that perfectly fit the panel). I also try to draw just one line with fixed parameters but I have the same problem.
public class NewMapPanel extends JPanel {
private static final long serialVersionUID = 1L;
private GameMap gameMap;
private Grid grid;
private JPanel contentPanel;
public NewMapPanel() {
this.setBackground(Color.white);
}
public void updateMap(GameMap gameMap) {
this.gameMap = gameMap;
...load the object into my custom object grid ...
contentPanel = new JPanel(new GridBagLayout());
contentPanel.setBackground(Color.GREEN);
GridBagConstraints c = new GridBagConstraints();
// draw the grid
for (City city : gameMap.getCities().values()) {
CityPanel cityPanel = new CityPanel(city, grid);
c = new GridBagConstraints();
c.gridx = grid.getColumn(city);
c.gridy = grid.getRow(city);
c.gridwidth = 1;
c.gridheight = 1;
c.fill = GridBagConstraints.BOTH;
c.anchor = GridBagConstraints.CENTER;
contentPanel.add(cityPanel, c);
}
add(contentPanel, BorderLayout.CENTER);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
contentPanel.setSize(super.getWidth(), super.getHeight());
grid.setSize(super.getWidth(), super.getHeight()); //to get the right parameters to be used into drawLine
for (City city1 : gameMap.getCities().values()) {
int x1 = grid.getBarycenterX(city1);
int y1 = grid.getBarycenterY(city1);
for (City city2 : city1.getAdjacentCities()) {
int x2 = grid.getBarycenterX(city2);
int y2 = grid.getBarycenterY(city2);
System.out.println("(" + x1 + "," + y1 + ") -> (" + x2 + "," + y2 + ")");
g.drawLine(x1, y1, x2, y2);
}
}
}
}