下面的这段代码只能画一个圆,后面画的圆将会清除前面的图形。我想保留以前所画的图形应该怎样实现?
望务位高手给一些建议,小弟不胜感激!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class SelfContainedPanel extends JPanel {
private int x1, y1, x2, y2;
// set up mouse event handling for SelfContainedPanel
public SelfContainedPanel()
{
// set up mouse listener
addMouseListener(
new MouseAdapter() { // anonymous inner class
// handle mouse press event
public void mousePressed( MouseEvent event )
{
x1 = event.getX();
y1 = event.getY();
}
// handle mouse release event
public void mouseReleased( MouseEvent event )
{
x2 = event.getX();
y2 = event.getY();
repaint();
}
} // end anonymous inner class
); // end call to addMouseListener
// set up mouse motion listener
addMouseMotionListener(
new MouseMotionAdapter() { // anonymous inner class
// handle mouse drag event
public void mouseDragged( MouseEvent event )
{
x2 = event.getX();
y2 = event.getY();
repaint();
}
} // end anonymous inner class
); // end call to addMouseMotionListener
} // end constructor SelfContainedPanel
// return preferred width and height of SelfContainedPanel
public Dimension getPreferredSize()
{
return new Dimension( 150, 100 );
}
// paint an oval at the specified coordinates
public void paintComponent( Graphics g )
{
super.paintComponent( g );
g.drawOval( Math.min( x1, x2 ), Math.min( y1, y2 ),
Math.abs( x1 - x2 ), Math.abs( y1 - y2 ) );
}
} // end class SelfContainedPanel
public class SelfContainedPanelTest extends JFrame {
private SelfContainedPanel myPanel;
// set up GUI and mouse motion event handlers for application window
public SelfContainedPanelTest()
{
// set up a SelfContainedPanel
myPanel = new SelfContainedPanel();
myPanel.setBackground( Color.YELLOW );
Container container = getContentPane();
container.setLayout( new FlowLayout() );
container.add( myPanel );
// set up mouse motion event handling
addMouseMotionListener(
new MouseMotionListener() { // anonymous inner class
// handle mouse drag event
public void mouseDragged( MouseEvent event )
{
setTitle( "Dragging: x=" + event.getX() +
"; y=" + event.getY() );
}
// handle mouse move event
public void mouseMoved( MouseEvent event )
{
setTitle( "Moving: x=" + event.getX() +
"; y=" + event.getY() );
}
} // end anonymous inner class
); // end call to addMouseMotionListener
setSize( 300, 200 );
setVisible( true );
} // end constructor SelfContainedPanelTest
public static void main( String args[] )
{
SelfContainedPanelTest application = new SelfContainedPanelTest();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class SelfContainedPanelTest