在JLabel Java Swing上绘制多个多边形

时间:2014-11-12 20:36:16

标签: java swing

我需要在图像标签上绘制10个多边形的10组坐标。这是我到目前为止编码的内容:

但是因为我无法单独调用paintComponent,所以在实例化JLabel时调用它会导致问题。最后,我只是在图像上绘制最后的多边形,因为每次创建新的jLabel时。有人可以指出如何改进它,以便我可以在同一个JLabel上绘制多个多边形。

private void setMapImage()
{
    Queries queries = new Queries(dbConnection, connection);
    List<ArrayList<Integer>> allGeo = queries.getBuilding();

    for(int i = 0; i < allGeo.size(); i++)
    {
        int[] xPoly = queries.separateCoordinates(allGeo.get(i),0);
        int[] yPoly = queries.separateCoordinates(allGeo.get(i),1);
        poly = new Polygon(xPoly, yPoly, xPoly.length);

        poly = new Polygon(xPoly, yPoly, xPoly.length);
        background=new JLabel(new ImageIcon("image.JPG"),SwingConstants.LEFT)
        {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.YELLOW);
                g.drawPolygon(poly);

            }
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(820, 580);
            }
        };
    }
    background.setVerticalAlignment(SwingConstants.TOP);
    frame.add(background);
    background.setLayout(new FlowLayout());
    frame.setVisible(true);
}

1 个答案:

答案 0 :(得分:0)

我认为你必须遍历JLabel的paintComponent方法中的多边形。在此之前,您必须将所有poligons添加到列表中。

例如:

private void setMapImage()
{
    Queries queries = new Queries(dbConnection, connection);
    List<ArrayList<Integer>> allGeo = queries.getBuilding();
    List<Polygon> polyList = new ArrayList<Polygon>();
    for(int i = 0; i < allGeo.size(); i++)
    {
        int[] xPoly = queries.separateCoordinates(allGeo.get(i),0);
        int[] yPoly = queries.separateCoordinates(allGeo.get(i),1);
        poly = new Polygon(xPoly, yPoly, xPoly.length);
        polyList.add(poly);
    }   
    background=new JLabel(new ImageIcon("image.JPG"),SwingConstants.LEFT)
    {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.setColor(Color.YELLOW);
            for(final Polygon poly : polyList){
                g.drawPolygon(poly);
            }
        }
        @Override
        public Dimension getPreferredSize() {
            return new Dimension(820, 580);
        }
    };

    background.setVerticalAlignment(SwingConstants.TOP);
    frame.add(background);
    background.setLayout(new FlowLayout());
    frame.setVisible(true);
}