This page contains an archived post to the Java Answers Forum made prior to February 25, 2002.
If you wish to participate in discussions, please visit the new
Artima Forums.
Message:
Use fillRect to erase the content
Posted by Kishori Sharan on January 31, 2001 at 2:36 PM
Hi Girish When you want to erase the lines from JPanel, then just draw and fill a rectangle of the same size as the panel and the lines will be erased. You need to set a flag that clear button was clicked and in paintComponent method of JPanle you need to use fillRect when you want to erase the lines. The following code draws a string on JPanle when you click on Draw button and then erases the string when you click on Clear button. Use also need to use the same color as the background of JPanle to fill the rectangle. Thanx Kishori ///////////////////////////// import java.awt.*; import java.awt.event.*; import java.applet.* ; import javax.swing.* ; public class Erase extends JFrame { JButton clear = new JButton ( "Clear" ) ; JButton draw = new JButton ( "Draw" ) ; PaintingPanel panel = new PaintingPanel ( ) ; JPanel buttonPanel = new JPanel ( ) ; public Erase ( ) { Container cp = getContentPane ( ) ; panel.setSize ( 400, 400 ) ; buttonPanel.add ( clear ) ; buttonPanel.add ( draw ) ; cp.add ( panel, "Center" ) ; cp.add ( buttonPanel, "South" ) ; draw.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { Erase.this.panel.setClear ( false ) ; Erase.this.panel.repaint ( ) ; } } ); clear.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { Erase.this.panel.setClear ( true ) ; Erase.this.panel.repaint ( ) ; } } ); } public static void main ( String[] args ) { Erase e = new Erase ( ) ; e.setBounds ( 20, 20 , 500, 500 ) ; e.show ( ) ; }
} class PaintingPanel extends JPanel { private boolean clear = false ; public void paintComponent( Graphics g ) { if ( !clear ) { g.drawString ( "Hello Girish" , 20 ,20 ) ; } else { // Draw and fill a rectangle of same size as the panel Rectangle r = this.getBounds ( ) ; g.setColor ( this.getBackground ( ) ) ; g.fillRect ( r.x, r.y, r.width, r.height ) ; clear = false ; } } public void setClear ( boolean clearFlag ) { clear = clearFlag ; } }
Replies:
|