0

此代码应创建一个黑色窗口,然后在其上添加一条线和多边形。

public class gui extends JFrame {

 JPanel pane = new JPanel();
 gui(String title){
    super(title);
    setBounds(100,100,500,500);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = this.getContentPane();
    pane.setBackground(new Color(0,0,0));
    con.add(pane);
    setVisible(true);
 }

 public void paint(Graphics g){

    g.drawLine(100, 100, 400, 400);

    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(250,0,0));
    g.fillPolygon(triangle);
 }
}

当我删除该paint()方法时,会按预期创建一个纯黑色的 GUI。

但是,当该paint()方法到位时,您会在白色背景上获得线条和多边形,而不是黑色背景。

如何使黑色背景显示出来?

4

1 回答 1

3

你需要打电话

super.paint(g);

在你的paint方法中。

在 Swing 中,首选的方法是覆盖,paintComponent尽管因为JFrame实际上不是,JComponent所以不会调用 this 方法。要使用这种方法,可以将功能移至自定义JComponent

于 2012-10-13T17:51:27.320 回答