为什么我的形状和图像在我的面板上消失? [英] Why do my shapes and images disappear on my panel?

查看:139
本文介绍了为什么我的形状和图像在我的面板上消失?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 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();




//获取坐标的方法:MousePressed,MouseReleased


解决方案不要在 paintComponent 下调用 repaint() / code>方法。另外,请在 paintComponent 方法中执行 super.paintComponent(g)



更新:您的代码有很多编译错误。然而,请看下面的变更列表:


  • new Rectangle2D(a,b,c,d )应该是新的 Rectangle2D.Float(10,10,100,100); 或者无论如何,a,b,c和d应该有一些值,否则它们都是零,所以没有矩形

  • 在定义和构造函数中命名该类

  • 实现 mouseClicked mouseEntered mouseExited

  • actionPerformed 中删除​​ g2D.draw(),并且不要保留对 g2D



如果您需要,我有完整的代码可用。


I have used the paintComponent method to draw shapes on my panel. However, every time I minimize the frame or resize it, they disappear. Not sure what to add to my code.

   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

解决方案

Don't call repaint() under the paintComponent method. Also, do super.paintComponent(g) the first thing in your paintComponent method.

Update: your code has a lot of compile errors. However, please see below a list of things to change:

  • new Rectangle2D(a, b, c, d) should be new Rectangle2D.Float(10, 10, 100, 100); or anyway, a, b, c and d should have some values, otherwise they are all zero, so no rectangle
  • name the class the same both in definition and in constructor
  • implement mouseClicked, mouseEntered and mouseExited
  • remove g2D.draw() from actionPerformed and don't keep a reference to g2D in the class.

I have the full code that is working if you need it.

这篇关于为什么我的形状和图像在我的面板上消失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆