Foros del Web » Programación para mayores de 30 ;) » Java »

[SOLUCIONADO] Borrar figuras geometricas con paint

Estas en el tema de Borrar figuras geometricas con paint en el foro de Java en Foros del Web. Hola Muchachos Bueno mi problema es que estoy haciendo una aplicación JAVA en la cual varias veces pinto distintas figuras, pero estas se me van ...
  #1 (permalink)  
Antiguo 14/11/2010, 19:22
Avatar de eaanillol  
Fecha de Ingreso: septiembre-2010
Ubicación: Bogota - Colombia
Mensajes: 25
Antigüedad: 13 años, 7 meses
Puntos: 0
De acuerdo Borrar figuras geometricas con paint

Hola Muchachos
Bueno mi problema es que estoy haciendo una aplicación JAVA en la cual varias veces pinto distintas figuras, pero estas se me van acumulando en el jframe, y la verdad no quiero que eso pase. Lo que quiero es que cuando el programa dibuje una nueva figura la anterior se borre. El proyecto lo estoy haciendo en Netbeans 6.9.

Nota: Si la variable figura = 1 se pinta un cuadrado
figura = 2 se pinta un circulo
Si la variable color = 1 se pinta de rojo
color = 2 se pinta de azul

Estructura
Hay dos clases:
Clase 1: Contiene el codigo del jframe y la funcion paint para pintar



package Frame;

import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

/**
*
* @author Administrador
*/
public class framePrueba extends javax.swing.JFrame implements ActionListener,
WindowListener{
public boolean actualizar = false;
public figuras f;
/** Creates new form framePrueba */
public framePrueba() {
f= new figuras(1,1);
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() {

pintar = new javax.swing.JButton();
figure = new javax.swing.JTextField();
color = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

pintar.setText("Pinta");
pintar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pintarActionPerformed(evt);
}
});

jLabel1.setText("Color");

jLabel2.setText("Figura");

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.TRAILI NG, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addGap(51, 51, 51)
.addComponent(pintar)
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED, 79, Short.MAX_VALUE)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)))
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.LEADING, false)
.addComponent(figure)
.addComponent(color, javax.swing.GroupLayout.DEFAULT_SIZE, 46, Short.MAX_VALUE))
.addGap(125, 125, 125))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(pintar)
.addComponent(figure, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.Component Placement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.G roupLayout.Alignment.BASELINE)
.addComponent(color, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addContainerGap(232, Short.MAX_VALUE))
);

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

private void pintarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int fig = Integer.parseInt(figure.getText());
int col = Integer.parseInt(color.getText());

if(!actualizar){
f = new figuras(fig,col);
actualizar = true;
} else
{
f.setColor(col);
f.setFigura(fig);

}
repaint();
}

public void paint(Graphics g)
{
try{
f.dibujando(g);

}catch (Exception e)
{
System.out.print("Los datos aun no han sido ingresados");
}
// repaint();
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/*java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new framePrueba().setVisible(true);
}
});*/
framePrueba f = new framePrueba();
f.setSize(500,500);
f.setVisible(true);
}

// Variables declaration - do not modify
private javax.swing.JTextField color;
private javax.swing.JTextField figure;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JButton pintar;
// End of variables declaration

public void actionPerformed(ActionEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowOpened(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowClosing(WindowEvent e) {
System.exit(0);
}

public void windowClosed(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowIconified(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowDeiconified(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowActivated(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

public void windowDeactivated(WindowEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}

}

--------------------------------------------------------------------------------------------------------
Clase 2: Se llama figura y contiene los metodos para dibujar la figura que se le indique desde el metodo paint del jframe.

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

package Frame;

import java.awt.Color;
import java.awt.Graphics;

/**
*
* @author Administrador
*/
public class figuras {

private int figura;
private int color;
public figuras(int figura, int color)
{
this.figura=figura;
this.color=color;
}

public void dibujando(Graphics g)
{


if(figura == 1)
{
if(color == 1){
g.setColor(Color.red);
g.fillRect(100, 100, 50, 50);
}else
{
g.setColor(Color.BLUE);
g.fillRect(100, 100, 50, 50);
}
}else
{
if(color == 1){
g.setColor(Color.red);
g.fillOval(100, 100, 50, 50);
}else
{
g.setColor(Color.BLUE);
g.fillOval(100, 100, 50, 50);
}
}
}

/**
* @param figura the figura to set
*/
public void setFigura(int figura) {
this.figura = figura;
}

/**
* @param color the color to set
*/
public void setColor(int color) {
this.color = color;
}
}


Gracias!!!!

Última edición por eaanillol; 14/11/2010 a las 19:24 Razón: Me equivoque colocando el titulo
  #2 (permalink)  
Antiguo 15/11/2010, 09:46
Avatar de eaanillol  
Fecha de Ingreso: septiembre-2010
Ubicación: Bogota - Colombia
Mensajes: 25
Antigüedad: 13 años, 7 meses
Puntos: 0
Respuesta: Borrar figuras geometricas con paint

Bueno, ya que nadie me dio la respuesta, me toco indagar, y en el libro de Deytel en la QUINTA edición se encuentra la respuesta.

Para borrar las figuras pintadas antes de empezar a dibujar con el objeto Graphics en la función paint(Graphics g), debemos llamar a la clase abstracta de paint e invocar el método paint (En esa versión java ese método aun se podía acceder), sin embargo el método actual que se puede acceder y nos da el mismo resultado se llama paintComponents, como se vé en la linea 5 ,asi:

Código java:
Ver original
  1. public void paint(Graphics g)
  2.     {
  3.         try{
  4.          
  5.          super.paintComponents(g);
  6.          f.dibujando(g);
  7.          
  8.         }catch (StackOverflowError e)
  9.         {
  10.          System.out.print("Los datos aun no han sido ingresados");
  11.         }
  12.         catch(Exception e)
  13.         {
  14.         System.out.print("Los datos aun no han sido ingresados");
  15.         }
  16.  
  17.     }
[/QUOTE]


Como pueden ver, agregué manejo excepciones por que el método paint al iniciar el programa es uno de lo primeros en ejecutarse y vota una excepción ya que el objeto f de la clase "figura" no ha sido inicializado.

Gracias y espero que esto les sirva de algo.
pd: Comentenme si les sirvió
  #3 (permalink)  
Antiguo 22/11/2010, 15:58
Avatar de eaanillol  
Fecha de Ingreso: septiembre-2010
Ubicación: Bogota - Colombia
Mensajes: 25
Antigüedad: 13 años, 7 meses
Puntos: 0
Respuesta: Borrar figuras geometricas con paint

1234567890

Etiquetas: borrar, figuras, paint
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:42.