java - 为什么jPanel不清除?

标签 java swing graphics jpanel

该程序在jPanel上绘制输入尺寸的椭圆形。当我改变绘制的圆圈的大小时,旧的圆圈不会消失。为什么?

代码:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  

    jPanel.Repaint();
    try{
        jLabel6.setText("");
        int a=Integer.parseInt(jTextField1.getText()); 

        Graphics2D gfx=(Graphics2D)jPanel1.getGraphics();
        gfx.setColor(Color.red);
        gfx.fillOval(100,50,a,a);
        gfx.fillOval(400,50,a,a);

    }catch(NumberFormatException e){
        jLabel6.setText("Incorrect data");
    }
}

最佳答案

使用覆盖的JPanel#paintComponent()方法而不是使用 JPanel#getGraphics() 方法。

不要忘记在重写的 paintComponent() 方法中调用 super.paintComponent(g);

JPanel jPanel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillOval(100, 50, c, c);
        g.fillOval(400, 50, c, c);
    }
};
<小时/>

--编辑--

代码中的更改:

// This is the code where you have create JPanel object
JPanel jPanel = new JPanel() {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);

        try{
            int c=Integer.parseInt(jTextField1.getText());//read the value

            g.setColor(Color.red);
            g.fillOval(100, 50, c, c);
            g.fillOval(400, 50, c, c);

        }catch(NumberFormatException e){//handle the exception} 
    }
};


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {  

    try{
        jLabel6.setText("");
        jPanel.repaint(); // simply call repaint method
    }catch(NumberFormatException e){
        jLabel6.setText("Incorrect data");
    }
}

关于java - 为什么jPanel不清除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23714245/

相关文章:

java - 选项卡布局的选项卡不显示任何内容

java - 停止 Swing 计时器

graphics - 如何检查线段和从与水平面成一定角度的点发出的线射线之间的交点?

opengl - 从剪辑空间到屏幕坐标的转换何时发生?

c++ - 用 C++ 编程的 DAW 使用什么来进行图形渲染和音频输出?

java - 从巨大的集合中遍历和分组相似对象的有效方法

java - 线程池任务执行器

java - JFrame 中的多个 JPanel

java - 面板内绘制的图像似乎有错误的 x,y 偏移

Java Regex 不匹配,有什么解释吗?