-3

我写了以下代码。一切正常。没有编译错误。但我只看到一个黄色的窗口,什么都没有。我在这里发布我的paintcomponent 方法。

我的paintcomponent方法

  @Override
    public void paintComponent(Graphics g)
    {super.paintComponent(g);
        g.setColor(Color.red);
        g.drawRect(x,100,150,200);
        fh++;
    }
    }

尝试扩展 Jpanel、JFrame、Jcomponent 等我尝试了 paint() 以及 paintComponent()

我正在添加完整代码以供参考 我的代码


import javax.swing.*;
import java.awt.*;
import static javax.swing.JFrame.EXIT_ON_CLOSE;

class painting extends JPanel
{static Component c=new Canvas();
 static JFrame f=new JFrame();
 int fh;
 int x=50;
    public void main(String args[]) throws InterruptedException
   {
    f.setDefaultCloseOperation(EXIT_ON_CLOSE);
    f.add(c);
     f.setVisible(true);   
     f.setSize(300,320);

     /*
     c.setSize(200,220);
     c.setBackground(Color.yellow);
     c.setForeground(Color.red);
     c.setVisible(true);
     */
     for(;x<200;x++)
     {x=x+10;
     repaint();
     Thread.sleep(10);
    }
    }
    @Override
    public void paintComponent(Graphics g)
    {super.paintComponent(g);
        g.setColor(Color.red);
        g.drawRect(x,100,150,200);
        fh++;
    }
    }
4

1 回答 1

0

paintComponent仅当将组件添加到窗口时才调用组件的方法。您new Canvas()在窗口中添加了一个,但您从未将您自己的专用面板的实例添加painting到您的窗口中。

您可以通过删除它来修复它:

static Component c=new Canvas();

并替换这个:

f.add(c);

有了这个:

f.add(new painting());
于 2019-10-01T14:05:03.520 回答