Java中填充点击区域

发布于 2024-10-06 19:01:38 字数 1915 浏览 0 评论 0原文

我正在开发一个关于图形着色(使用 GUI)的项目。我有一张地图,分为小多边形。当我单击其中一个多边形时,我希望它用特定的颜色填充。我怎样才能做到这一点?

我的事件侦听器已全部设置完毕。我可以识别我点击的区域。所以,我对要为哪个多边形着色没有问题。我尝试了 fillPolygon(Polygon p) 方法来做到这一点,但它不起作用。实际上,它填充了我想要的多边形;但是,当我单击另一个多边形时,它会为新多边形着色并擦除旧多边形。我想我知道是什么原因造成的:我将 fillPolygon(Polygon p) 放置在 PaintComponent(Graphics g) 方法中,每次启动程序时,该方法都会在面板上绘制完整的地图。

我的 Map 类中有这个方法,用于在面板上绘制地图。

public void draw ( Graphics screen ) {
   screen.setColor ( Color.BLACK );
   for ( Polygon thePoly : theShapes ) 
      screen.drawPolygon ( thePoly.getPolygon() );
}

另外,我的 MapPanel 类中有以下几行。

import java.awt.*;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.*;

public class MapPanel extends JPanel {

  private Map theMap;           // collection of Regions to be colored

  /* Some other variables here */

  public MapPanel() {
      theMap = new Map( );
      this.addMouseListener( new ClickListener() );
  }

  public JMenuBar getMenu() {
      /* Bunch of lines for the main panel, menus etc... */
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent(g);
    theMap.draw ( g );
    if( j != null )
        g.fillPolygon( j.getPolygon() );
  } 

  private class ClickListener implements MouseListener
  {
      public void mousePressed (MouseEvent event)
      {
         Point p = event.getPoint();

         for(int i = 0; i < theMap.theShapes.size(); i++){
            if( theMap.theShapes.get(i).getPolygon().contains( p ) ) {
                j = theMap.theShapes.get(i);
            }
         }
         repaint();
      }
      public void mouseClicked (MouseEvent event) {}
      public void mouseReleased (MouseEvent event) {}
      public void mouseEntered (MouseEvent event) {}
      public void mouseExited (MouseEvent event) {}
  }

  /* Other listener classes */
}

如何单独使用 fillPolygon(Polygon p) 方法?

提前致谢。

I'm working on a project about graph-coloring (with GUI). I have a map divided into little polygons. When I clicked on one of these polygons, I want it to be filled with a specific color. How can I do that?

I got my event listeners all set. I can recognize the area that I clicked on. So, I have no problem with which polygon I'm going to color. I tried the fillPolygon(Polygon p) method to do that, it didn't work. Actually, it filled the polygon that I want; but, when I clicked on another polygon, it colored the new one and erased the older one. I think I know what is causing this: I placed the fillPolygon(Polygon p) in the paintComponent(Graphics g) method which draws the complete map on my panel everytime I started the program.

I have this method in my Map class, to draw the map on the panel.

public void draw ( Graphics screen ) {
   screen.setColor ( Color.BLACK );
   for ( Polygon thePoly : theShapes ) 
      screen.drawPolygon ( thePoly.getPolygon() );
}

Also, I have following lines in my MapPanel class.

import java.awt.*;
import javax.swing.JPanel;
import javax.swing.*;
import java.awt.event.*;

public class MapPanel extends JPanel {

  private Map theMap;           // collection of Regions to be colored

  /* Some other variables here */

  public MapPanel() {
      theMap = new Map( );
      this.addMouseListener( new ClickListener() );
  }

  public JMenuBar getMenu() {
      /* Bunch of lines for the main panel, menus etc... */
  }

  public void paintComponent( Graphics g ) {
    super.paintComponent(g);
    theMap.draw ( g );
    if( j != null )
        g.fillPolygon( j.getPolygon() );
  } 

  private class ClickListener implements MouseListener
  {
      public void mousePressed (MouseEvent event)
      {
         Point p = event.getPoint();

         for(int i = 0; i < theMap.theShapes.size(); i++){
            if( theMap.theShapes.get(i).getPolygon().contains( p ) ) {
                j = theMap.theShapes.get(i);
            }
         }
         repaint();
      }
      public void mouseClicked (MouseEvent event) {}
      public void mouseReleased (MouseEvent event) {}
      public void mouseEntered (MouseEvent event) {}
      public void mouseExited (MouseEvent event) {}
  }

  /* Other listener classes */
}

How can I use the fillPolygon(Polygon p) method individually?

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

狠疯拽 2024-10-13 19:01:38

alt text

正如 Tim 所说,您需要一个辅助数据结构来跟踪每个多边形的颜色和选择状态。请参阅我的此处的示例代码

package polygonexample;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author ndunn
 */
public class PolygonExample extends JPanel {

    private static final int NUM_POLYGONS = 20;

    private List<MapPolygon> polygons;

    private static final int WIDTH = 600;
    private static final int HEIGHT = 600;
    private Random random = new Random();
    public PolygonExample() {

        polygons = new LinkedList<MapPolygon>();
        for (int i = 0; i < NUM_POLYGONS; i++) {
            int x1 = random.nextInt(WIDTH);
            int x2 = random.nextInt(WIDTH);
            int x3 = random.nextInt(WIDTH);

            int y1 = random.nextInt(HEIGHT);
            int y2 = random.nextInt(HEIGHT);
            int y3 = random.nextInt(HEIGHT);

            int r = random.nextInt(255);
            int g = random.nextInt(255);
            int b = random.nextInt(255);
            Color randomColor = new Color(r,g,b);

            polygons.add(new MapPolygon(new int[]{x1,x2,x3}, new int[]{y1,y2,y3}, 3, randomColor));
        }

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                for (MapPolygon mapPiece : polygons) {
                    if (mapPiece.contains(e.getPoint())) {
                        mapPiece.setSelected(!mapPiece.isSelected());
                        repaint();
                        break;
                    }
                }
            }
        });
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(WIDTH, HEIGHT);
    }



    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        final Color outlineColor = Color.BLACK;
        for (MapPolygon mapPiece : polygons) {
            if (mapPiece.isSelected()) {
                g.setColor(mapPiece.getFillColor());
                g.fillPolygon(mapPiece);
            }
            else {
                g.setColor(outlineColor);
                g.drawPolygon(mapPiece);
            }
        }
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel panel = new PolygonExample();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private class MapPolygon extends Polygon {

        private boolean selected;
        private Color fillColor;

        public MapPolygon(int[] xpoints, int[] ypoints, int npoints, Color color) {
            super(xpoints, ypoints, npoints);
            this.fillColor = color;
            this.selected = false;
        }

        public Color getFillColor() {
            return fillColor;
        }

        public void setFillColor(Color fillColor) {
            this.fillColor = fillColor;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

}

alt text

As Tim says, you need an ancillary data structure to keep track of the color and selection state of each polygon. See my example code here

package polygonexample;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Polygon;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 *
 * @author ndunn
 */
public class PolygonExample extends JPanel {

    private static final int NUM_POLYGONS = 20;

    private List<MapPolygon> polygons;

    private static final int WIDTH = 600;
    private static final int HEIGHT = 600;
    private Random random = new Random();
    public PolygonExample() {

        polygons = new LinkedList<MapPolygon>();
        for (int i = 0; i < NUM_POLYGONS; i++) {
            int x1 = random.nextInt(WIDTH);
            int x2 = random.nextInt(WIDTH);
            int x3 = random.nextInt(WIDTH);

            int y1 = random.nextInt(HEIGHT);
            int y2 = random.nextInt(HEIGHT);
            int y3 = random.nextInt(HEIGHT);

            int r = random.nextInt(255);
            int g = random.nextInt(255);
            int b = random.nextInt(255);
            Color randomColor = new Color(r,g,b);

            polygons.add(new MapPolygon(new int[]{x1,x2,x3}, new int[]{y1,y2,y3}, 3, randomColor));
        }

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                for (MapPolygon mapPiece : polygons) {
                    if (mapPiece.contains(e.getPoint())) {
                        mapPiece.setSelected(!mapPiece.isSelected());
                        repaint();
                        break;
                    }
                }
            }
        });
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(WIDTH, HEIGHT);
    }



    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        final Color outlineColor = Color.BLACK;
        for (MapPolygon mapPiece : polygons) {
            if (mapPiece.isSelected()) {
                g.setColor(mapPiece.getFillColor());
                g.fillPolygon(mapPiece);
            }
            else {
                g.setColor(outlineColor);
                g.drawPolygon(mapPiece);
            }
        }
    }



    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        JPanel panel = new PolygonExample();
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private class MapPolygon extends Polygon {

        private boolean selected;
        private Color fillColor;

        public MapPolygon(int[] xpoints, int[] ypoints, int npoints, Color color) {
            super(xpoints, ypoints, npoints);
            this.fillColor = color;
            this.selected = false;
        }

        public Color getFillColor() {
            return fillColor;
        }

        public void setFillColor(Color fillColor) {
            this.fillColor = fillColor;
        }

        public boolean isSelected() {
            return selected;
        }

        public void setSelected(boolean selected) {
            this.selected = selected;
        }
    }

}
绿光 2024-10-13 19:01:38

听起来您需要将PolygonColor保存为将来渲染的属性。如果不知道你是如何构建你的 UI 代码的,或者没有一些你认为哪里出了问题的样本,就很难回答。

It sounds like you need to save the Color of the Polygon as an attribute for future renderings. Without knowing how you structured your UI code or having some sample of where you think things went wrong, it is hard to answer.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文