为什么我的面板上的形状和图像消失了?

nsc*_*010 1 java graphics swing shapes paintcomponent

我已经使用该paintComponent方法在我的面板上绘制形状.但是,每次我最小化帧或调整大小时,它们都会消失.不确定要添加到我的代码中的内容.

   public class ShapePanel extends JPanel implements ActionListener, MouseListener{

    int a,b,c,d;
    Graphics2D g2D;
    private Rectangle2D rect = new Rectangle2D(a,b,c-a,d-b);

    public ShapePanel(){

    addMouseListener(this);
    setLayout(new GridLayout());
}

    public void paintComponent(Graphics g) {

    g2D = (Graphics2D) g;
    g2D.draw(rect);
    repaint();

}


   //get methods for coordinates: MousePressed, MouseReleased
Run Code Online (Sandbox Code Playgroud)

Dan*_* D. 5

不要repaint()paintComponent方法下打电话.另外,super.paintComponent(g)在你的paintComponent方法中做第一件事.

更新:您的代码有很多编译错误.但是,请参阅下面的要更改的列表:

  • new Rectangle2D(a, b, c, d)应该是新的Rectangle2D.Float(10, 10, 100, 100);或者无论如何,a,b,c和d应该有一些值,否则它们都是零,所以没有矩形
  • 在定义和构造函数中将类命名为相同
  • 实施mouseClicked,mouseEnteredmouseExited
  • g2D.draw()从班级中删除actionPerformed并不保留引用g2D.

如果需要,我有完整的代码.