paintComponent does not work if its called by the recursive function?

前端 未结 2 1580
后悔当初
后悔当初 2020-11-27 23:54
  1. I want to see all the Points one after another but I see only able to see 1 point. What shold I change to see all the Points ?
  2. In the
2条回答
  •  天命终不由人
    2020-11-28 00:34

    1: first line of paintComponent() should be your super.paintComponent()

    2: why are you calling super.repaint(), make it simply repaint()

    Your Drow should be like this.

    public class drow extends JPanel {
     ...........
    @Override
    public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 =(Graphics2D) g;
    
    }
    public void set_list(LinkedList  p){
    Points =p;     
    repaint();
    }
    

    try with this. i hope this is simply a structure, your paintComponent() isn't drawing anything.

    EDIT

    public void set_list(LinkedList  p){
    Points =p;     
    System.out.println("set_ist");// 1:First this line will be displayed then..
    repaint();//2: Then this is called, which in turn calls your `paintComponent()`
    }
    

    Now when your paintComponent() is called it has

    system.out.println("paintComponent");
    //3: so now this will be displayed.
    

    Where is the problem here?

    EDIT- SWING TIMER

    Your code was ok, but the function processing is way faster than GUI updation, thats why you were unable to see the changes in front of you. The way you were doing, of calling thread.sleep() between function calls to slow down it's call, was not a good approach. For any timing thing's in swing, use swing timer, i changed your code for swing timer.

    Using Swing Timer:

    public class exampe extends JPanel implements ActionListener {
    
        int x;
        int y;
        int temp = 0;
    
        public void paintComponent(Graphics g) {
    
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.fillOval(x - 2, y - 2, 4, 4);
        }
    
        public void set(int X, int Y) {
    
            x = X;
            y = Y;
        }
    
        public static void main(String args[]) {
    
            JFrame frame = new JFrame("TEST");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            exampe ex = new exampe();
            JScrollPane scroll = new JScrollPane(ex);
            frame.getContentPane().add(scroll);
            frame.setSize(400, 300);
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
            Timer PointTimer = new Timer(1000, ex);
            PointTimer.setInitialDelay(1000);
            PointTimer.start();
            System.out.println("started");
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
    
           // set(rand.nextInt(350), rand.nextInt(350));
              set(temp+10,temp+10);
              temp=temp+2;
              repaint();
        }
    }
    

提交回复
热议问题