简体   繁体   中英

In Java, repaint() doesn't call paintcomponent()

For a homework assignment I have to make a Java program that draws a red circle on a jframe when clicking a "start" button. When clicking the button, the method setSmallCircle is called. This does work, but inside this method I'm making a calling repaint() , but this doesn't seem to call the paintComponent method.

This is my code so far:

import java.awt.*;
import javax.swing.*;
class ReactionPanel extends JPanel {
  Color color;
  int size;
  public void paintComponent(Graphics g){
    System.out.println("paintcomp 1");
    super.paintComponent(g);
    System.out.println("paintcomp 2");
    g.setColor(color);
    g.fillOval(200, 200, size, size);
  }
  public void setSmallCircle(Color c){
    color = c;
    size = 10;
    System.out.println("drawing");
    repaint();
    System.out.println("repaint called");
  }
}

The method setSmallCircle(Color.red) is called by some other class. Does anyone know why the "repaint()" isn't drawing a red circle?

Any update to the painting of swing component should be inside EDT (eevent dispatch thread) . However while experimenting following portion:

public void paintComponent(Graphics g){
    System.out.println("paintcomp 1");

    super.paintComponent(g);
    g.setColor(color);
    System.out.println(color); // print color as null
    g.fillOval(20, 20, size, size); // printing size as 0

    System.out.println(size);

  }

updating color and size in setSmallCircle() is not taking effect !! paintComponent seems to keep using the old value, instead of updated value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM