【问题标题】:Draw multiple polygons on a JLabel Java Swing在 JLabel Java Swing 上绘制多个多边形
【发布时间】:2014-11-13 05:16:42
【问题描述】:

我需要在图像标签上绘制 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);
}

【问题讨论】:

  • 我不确定为什么要专门在 JLabel 上绘画。您是否考虑过使用玻璃板。这是Java tutorial,以防您想查看它。

标签: java swing


【解决方案1】:

我认为您必须遍历 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);
}

【讨论】:

  • 是的,它成功了!非常感谢
猜你喜欢
  • 2014-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多