简体   繁体   English

paintComponent未调用

[英]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. 窗口已创建,但未调用paintComponent()

repaint() in public Drawer() seems to do nothing. public Drawer() repaint()似乎无能为力。

How do I call paintComponent() ? 如何调用paintComponent()

You need to add the Drawer component to your JFrame : 您需要将Drawer组件添加到JFrame

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

No need to explicitly call paintComponent . 无需显式调用paintComponent Also, calling repaint() in the Drawer component is unnecessary. 同样,不需要在Drawer组件中调用repaint()

The above displaces your pane JPanel so you may want to re-think the layout of your frame. 上面的代码替换了您的pane JPanel因此您可能需要重新考虑框架的布局。

You created a new JComponent called Drawer , which does the drawing on itself . 您创建了一个名为Drawer的新JComponent ,该JComponent 自行绘制。 So, you have to add an instance of it to your Frame. 因此,您必须将其实例添加到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. 如果您不更改组件上的绘制内容,则无需手动调用repaint() The Swing framework will call it for you, for example when the window-size changes. 例如,当窗口大小更改时,Swing框架将为您调用它。

Also, class-names should start upper-case. 同样,类名应以大写字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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