此处的代码应创建一个窗口,然后在其上绘制一个多边形。
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);
}
}
窗口已创建,但paintComponent()
未被调用。
repaint()
在public Drawer()
似乎什么都不做。
我怎么打电话paintComponent()
?