我正在尝试绘制一个连接6个点的多边形,这些点在屏幕上被点击但是它不起作用

时间:2014-04-16 22:42:01

标签: java polygon

有人可以帮我弄清楚这段代码有什么问题吗?我正在尝试编写一个使用GUI界面的Java程序。该程序应该绘制一个多边形,连接在屏幕上点击的六个点。我很困惑,我似乎无法找到错误。

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
import java.applet.*;    
import java.net.*;      
import java.io.*;   

public class PolygonDrawer extends JFrame implements MouseListener
{


   private JLabel label;

   private ArrayList<Integer> xPoints = new ArrayList<Integer>(5); //add x values to ArrayList when clicked.
   private ArrayList<Integer> yPoints = new ArrayList<Integer>(5); //add y values to ArrayList when clicked.
   private int [] xArray = new int [5]; //copy the values from ArrayList of x values
   private int [] yArray = new int [5]; // copy the values from ArrayList of y values 
   private int count = 0; //keep count of how many times the mouse is clicked.

   public PolygonDrawer()
   {
      setTitle("Polygon Drawer with Sound");
      setSize(900,900);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);
      this.addMouseListener(this);


   }
   public void mouseClicked(MouseEvent me)
   {

      xPoints.add(me.getX());
      yPoints.add(me.getY());
      count++;

      repaint();
   }
   public void mouseReleased(MouseEvent e)
   { 
   }
   public void mouseEntered(MouseEvent e)
   {
   }
   public void mouseExited(MouseEvent e)
   {
   }
   public void mousePressed(MouseEvent e) 
   {
   }
   public static void main (String [] args)
   {
      new PolygonDrawer();
   }
   public void paint(Graphics g)
   {
      super.paint(g);
      if(count==6)
      {
         for(int i =0 ;i<5;i++)
         {
            xArray[i]=xPoints.get(i);
            yArray[i]=yPoints.get(i);
         }

         g.fillPolygon(xArray,yArray,6);

      }



   }

}

1 个答案:

答案 0 :(得分:1)

您的for循环没有循环足够的时间来遍历整个数组。它只会获得前5个元素。作为一般规则,您需要将i增加到数组的长度。因此,将for循环更改为:

 for(int i = 0; i < 6; i++) // 6 is the number of points so that's what you need to go to.
 {
   xArray[i]=xPoints.get(i);
   yArray[i]=yPoints.get(i);
 }

此外,您的绘图方法对于摆动组件略有不同。您应该按照this tutorial中的说明进行绘制。所以你的完整方法将如下所示:

class MyPanel extends JPanel {

public MyPanel() {
    setBorder(BorderFactory.createLineBorder(Color.black));
}

public void paintComponent(Graphics g) {
    super.paintComponent(g);       
 if(count==6)
  {
    for(int i = 0; i < 6; i++)  {
        xArray[i]=xPoints.get(i);
        yArray[i]=yPoints.get(i);
       }
  }
    }  
}

在构造函数中,您需要添加:

getContentPane().add(new MyPanel());

在将框架设置为true之前,或者它不会被绘制。