为什么jPanel不清楚?

时间:2014-05-17 17:34:09

标签: 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");
    }
}

1 个答案:

答案 0 :(得分:3)

使用重写的JPanel#paintComponent()方法,而不是使用JPanel#getGraphics()方法。

不要忘记在覆盖super.paintComponent(g);方法中致电paintComponent()

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");
    }
}