paint方法被多次调用...如何限制?

时间:2013-12-20 16:15:22

标签: java swing paint repaint

   // A program for drawing simple graphs
    public class Graphpane extends JPanel { 

    int node,i,j,flag;  // node is for storing no. of nodes... i,j are counters.. flag is for storing option yes or no
    ArrayList<Integer> xaxis= new ArrayList<Integer>(); // arraylist for storing x-cordinates
    ArrayList<Integer> yaxis= new ArrayList<Integer>(); //arraylist for storing y ordinates
    Scanner in= new Scanner(System.in);

    public Graphpane(){

        super();
        System.out.println("Create your own graph!!! :)");
        System.out.println("Enter the number of nodes in your graph:");
        node= in.nextInt();
        System.out.println("Enter the x and the y vertices respectively");
        System.out.println("<<<x cordinate shouldn't exceed 600 and y ordinate shouldn't exceed 400>>>");
        for(i=0;i<node;i++)
        {
            System.out.println("Enter the x co-ordinate for"+ i+ "node");
            xaxis.add(in.nextInt());
            System.out.println("Enter the y ordinate for"+ i+ "node");
            yaxis.add(in.nextInt());
        }
        repaint();
    }

    public void paint(Graphics g) // paint method
    {
        for(i=0;i<node;i++)
        {
            g.fillArc(xaxis.get(i)- 3, yaxis.get(i)-3,6,6,0,360);// drawing  points on panel
        }
                for(i=0;i<node;i++){    
            for(j=0;j<node;j++)  // asking whether the two points are connected or not.. if connected then drawing a line between the two
            {
                if(i==j)  // would skip for the same points as simple graph.. no loops
                {
                    continue;
                }
                else{
                    System.out.println("Are the points of index  "+i+   "  and  "+j+"  connected?? Say 1 for yes or else for no");
                    flag=in.nextInt(); // flag for recording whether connected or not
                    if(flag==1)
                    {
                         g.drawLine(xaxis.get(i),yaxis.get(i),xaxis.get(j),yaxis.get(j));
   }
        //xaxis is arraylist containing x cordinates and yaxis for containing y ordinates.. i and j are indices         
        //drawing lines between the two points if connected         
                    }
     //**Here I am asked whether my two points are connected question multiple times but I want it just once**                  

                }
            }
    }
    }

1 个答案:

答案 0 :(得分:3)

  

多次调用paint方法......如何限制?

你做不到。当程序调用自身重绘或Swing RepaintManager确定何时需要重新绘制组件时,组件将重新绘制它。

//**Here I am asked whether my two points are connected 
//question multiple times but I want it just once**  

绘画方法仅适用于绘画。应该没有用户交互。也就是说,您不应该显示选项窗格或任何其他类型的消息供用户响应。

因此,与用户交互的代码需要在paintComponent()方法之外进行编码。

此外,自定义绘制应该在paintComponent()方法中完成,而不是paint()方法。