【发布时间】:2016-07-04 13:08:03
【问题描述】:
我有一个扩展 JPanel 的 MapPanel 类。我在这个网格中显示了一些对象,我希望其中一些通过一条线连接起来。所以我试图将这条线绘制到 MapPanel.paintComponent 中,但我没有显示任何线。 我通过 System.out.println() 检查了行参数 (x1,y1,x2,y2),它们是正确的(0
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);
}
}
}
}
【问题讨论】:
-
我们没有City类,请发minimal reproducible example我们可以复制粘贴,当我们这样做时,它应该编译并显示您的问题
-
覆盖
getPreferredSize()和pack()封闭窗口以建立初始几何。 -
我应该在哪里做呢?在什么方面?
标签: java swing draw lines gridbaglayout