GridBagLayout上的DrawLine没有显示任何内容

时间:2016-07-04 13:08:04

标签: java swing draw lines gridbaglayout

我有一个扩展JPanel的MapPanel类。我在这个网格中显示一些对象,我希望它们中的一些通过一条线链接。所以我试图将这些行绘制到MapPanel.paintComponent中,但我没有显示任何行。 我通过System.out.println()检查线参数(x1,y1,x2,y2)并且它们是正确的(0< param< 600的种类,完全适合面板的度量)。我也尝试用固定参数绘制一行,但我遇到了同样的问题。

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);

            }
        }


    }

}

1 个答案:

答案 0 :(得分:0)

您是否尝试过设置颜色? g.setColor(Color.black);