【问题标题】:Why do my shapes and images disappear on my panel?为什么我的形状和图像在我的面板上消失了?
【发布时间】:2013-01-23 11:02:43
【问题描述】:

我使用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

【问题讨论】:

    标签: java swing graphics paintcomponent shapes


    【解决方案1】:

    不要在paintComponent 方法下调用repaint()。另外,在paintComponent 方法中首先执行super.paintComponent(g)

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

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

    如果你需要的话,我有完整的代码。

    【讨论】:

    • 如果这样做,我的面板上看不到任何矩形?
    • 我已经发现了一些错误,但请发布整个课程。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    相关资源
    最近更新 更多