简体   繁体   中英

paintComponent not called

This here code should create a window and then draw a polygon on it.

import java.awt.*;
import javax.swing.*;

public class gui extends JComponent {
  gui(String title){
    JPanel pane = new JPanel();
    JFrame frame = new JFrame(title);
    Container con = frame.getContentPane();
    con.add(pane);
    frame.setBounds(100,100,500,500);
    frame.setVisible(true);
  }
  public static void main(String[] args){
    gui myGUI = new gui("test");
    new Drawer();
    repaint();
  }
}
class Drawer extends JComponent {
  public Drawer() {
    System.out.println("drawer");
    repaint();
  }
  public void paintComponent(Graphics g) {
    super.paintComponent(g);     
    System.out.println("drawerpC");  

    Point p1 = new Point(400, 100);
    Point p2 = new Point(100, 300);
    Point p3 = new Point(200, 400);

    int[] xs = { p1.x, p2.x, p3.x };
    int[] ys = { p1.y, p2.y, p3.y };
    Polygon triangle = new Polygon(xs, ys, xs.length);

    g.setColor(new Color(255,255,255));
    g.fillPolygon(triangle);
  }  
}

The window is created, but paintComponent() is not called.

repaint() in public Drawer() seems to do nothing.

How do I call paintComponent() ?

You need to add the Drawer component to your JFrame :

Drawer drawer = new Drawer();
con.add(drawer);

No need to explicitly call paintComponent . Also, calling repaint() in the Drawer component is unnecessary.

The above displaces your pane JPanel so you may want to re-think the layout of your frame.

You created a new JComponent called Drawer , which does the drawing on itself . So, you have to add an instance of it to your Frame.

Drawer drawer = new Drawer();
con.add(drawer);

Manually calling repaint() shouldn't be necessary if you don't change what is painted on the component. The Swing framework will call it for you, for example when the window-size changes.

Also, class-names should start upper-case.

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