Limpando um Jpanel

0 respostas
C

Bom galera, montei um painel para desenhar.
Até ai está tudo Ok, porém criei um menu e uma opção que seria de Acabar essa tela, para a pessoa poder desenhar um novo desenho porem estou com dificuldade em relação a isso, pois não está apagando a tela.
Abaixo está o meu codigo

Tela principal:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * TelaDesenho.java
 *
 * Created on 26/11/2011, 18:40:51
 */
/**
 *
 * @author Usuario
 */
public class TelaDesenho extends javax.swing.JFrame {

    /** Creates new form TelaDesenho */
    public TelaDesenho() {
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        PainelDesenho = new Desenhar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        LimparTela = new javax.swing.JMenuItem();
        jMenuItem2 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem3 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout PainelDesenhoLayout = new javax.swing.GroupLayout(PainelDesenho);
        PainelDesenho.setLayout(PainelDesenhoLayout);
        PainelDesenhoLayout.setHorizontalGroup(
            PainelDesenhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 452, Short.MAX_VALUE)
        );
        PainelDesenhoLayout.setVerticalGroup(
            PainelDesenhoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        jMenu1.setText("Arquivo");
        jMenu1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenu1ActionPerformed(evt);
            }
        });

        LimparTela.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_A, java.awt.event.InputEvent.ALT_MASK));
        LimparTela.setText("Limpar Tela");
        LimparTela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                LimparTelaActionPerformed(evt);
            }
        });
        jMenu1.add(LimparTela);

        jMenuItem2.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.ALT_MASK));
        jMenuItem2.setText("Sair");
        jMenu1.add(jMenuItem2);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Sobre");

        jMenuItem3.setText("jMenuItem3");
        jMenu2.add(jMenuItem3);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PainelDesenho, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(PainelDesenho, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

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

}

private void LimparTelaActionPerformed(java.awt.event.ActionEvent evt) {
Desenhar bt = new Desenhar();
bt.limpar();
}

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TelaDesenho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TelaDesenho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TelaDesenho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TelaDesenho.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new TelaDesenho().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JMenuItem LimparTela;
    private javax.swing.JPanel PainelDesenho;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    // End of variables declaration
}
Classe Desenhar
import java.awt.Point;  
import java.awt.Graphics;  
import java.awt.event.MouseEvent;  
import java.awt.event.MouseMotionAdapter;  
import javax.swing.JPanel;  
import javax.swing.JLabel;  
import java.awt.Color;  
  
  
public class Desenhar extends JPanel  
        
{     
   private JLabel statusBar;  
   private int pointC = 0;
   private int pointCount = 0; // número de contagem de pontos  
   // array de 10000 referências java.awt.Point  
   private Point points[] = new Point[ 10000 ];  
     
   // configura a GUI e registra handler de evento de mouse  
   public Desenhar()  
   {  
        
      setBackground(Color.WHITE);   
      statusBar = new JLabel( "Mouse Fora da Área" );             
     
      
      // trata evento de movimento de mouse do frame  
      addMouseMotionListener(  
  
         new MouseMotionAdapter()// classe interna anônima  
         {    
            // armazena coordenadas de arrastar e repinta  
            public void mouseDragged( MouseEvent event )                  
            {           
               statusBar.setText( String.format( "Dragged at [%d, %d]",   
                event.getX(),event.getY() ) );  
               if ( pointCount < points.length )                          
               {         
                  points[ pointCount ] = event.getPoint(); // localiza o ponto  
                  pointCount++; // incrementa número de pontos em array  
                  repaint(); // repinta JFrame  
               } // fim do if  
            } // fim do método mouseDragged  
            public void mouseMoved( MouseEvent event )  
            {  
                statusBar.setText( String.format( "Moved at [%d, %d]",   
                event.getX(),event.getY() ) );  
            } // fim do método mouseMoved  
  
         } // fim da classe interna anônima  
      ); // fim da chamada para addMouseMotionListener  
   } // fim do construtor PaintPanel  
  
   // desenha oval em um quadro delimitador de 4x4 no local especificada na janela  
   public void paintComponent( Graphics g )  
   {  
      super.paintComponent( g ); // limpa a área de desenho  
  
      // desenha todos os pontos no array  
      for ( int i = 0; i < pointCount; i++ )  
         g.fillOval( points[ i ].x, points[ i ].y, 5, 5 );  
           
        
   } // fim do método paintComponent  
   public JLabel status(){  
        return statusBar;  
   }  
   public void limpar(){  
          Graphics clean = this.getGraphics();  
        for ( int i = 0; i < pointC; i++ )  
            clean.clearRect(points[ i ].x, points[ i ].y, 5, 5);  
        repaint();  
        pointC = 0; 
         
   }

}
Criado 26 de novembro de 2011
Respostas 0
Participantes 1