首页 > 解决方案 > (JAVA)如何区分二维对象

问题描述

一个简单的问题。我尝试使用图形 2d 来制作对象。我的问题是我们如何区分两个对象之间的变量。例如下面的代码;

 public void paintComponent(Graphics g) {
        super.paintComponent(g);
        
         r1 = new Rectangle(10, 10, 50, 30);
         r2 = new Rectangle(450, 10, 50, 30);
        
    
           g.setColor(Color.BLUE);
            g.fillRect(10, 10, 50, 30);
              
            g.setColor(Color.RED);
            g.fillRect(450, 10, 50, 30);
            
    }

public void actionPerformed(ActionEvent e) {

     if (r1.intersects(r2)) {..............
}

从上面的代码中,我有 2 个矩形变量 r1 和 r2,我可以在 actionPerformed 方法中执行“if (r1.intersects(r2))”。

但是使用Graphic2d时下面的代码怎么样,我如何区分这两个三角形,以便它可以适应“if(r1.intersects(r2))”,因为只有一个变量“lukis”只存在并且它用于做2个三角形。谢谢你。

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    
    Graphics2D lukis = (Graphics2D) g;
    
    int[] x = {100, 200, 300};
    int[] y = {300, 100, 300};
    
    lukis.setColor(Color.RED);
    lukis.drawPolygon(x, y, 3);
    
    int[] x1 = {600, 700, 800};
    int[] y1 = {300, 100, 300};
    
    lukis.setColor(Color.RED);
    lukis.drawPolygon(x1, y1, 3);
}

标签: java

解决方案


推荐阅读