// David Greenstein
// March 13, 2013
// SimpleStamper.java
// This program stamps rectangles and ovals using the mouse and meta key.
// Shift-mouse clears the window.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SimpleStamper
{
JFrame frame;
DisplayStamp canvas;
public static void main(String[] args)
{
SimpleStamper ss = new SimpleStamper();
ss.Run();
}
public void Run()
{
// Create a frame to hold everything
frame = new JFrame ("Hear Mouse");
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setBackground(Color.black); // only needed if frame is larger than panel
// Define panel to draw on
canvas = new DisplayStamp(); // create a panel to draw on
canvas.setBackground(Color.lightGray);
frame.addMouseListener(canvas); // connects the MouseListerner to the panel window
// Put frame together
frame.getContentPane().add(canvas); // puts panel on frame
frame.setVisible(true);
}
} // end class SimpleStamper
class DisplayStamp extends JPanel implements MouseListener
{
DisplayStamp()
{
setBackground(Color.black);
addMouseListener(this);
}
public void mousePressed(MouseEvent evt)
{
if ( evt.isShiftDown() )
{
repaint();
return;
}
int x = evt.getX();
int y = evt.getY();
Graphics g = getGraphics();
if ( evt.isMetaDown() )
{
g.setColor(Color.blue);
g.fillOval( x - 30, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawOval( x - 30, y - 15, 60, 30 );
}
else
{
g.setColor(Color.red);
g.fillRect( x - 30, y - 15, 60, 30 );
g.setColor(Color.black);
g.drawRect( x - 30, y - 15, 60, 30 );
}
g.dispose();
} // end mousePressed();
public void mouseEntered(MouseEvent evt) { }
public void mouseExited(MouseEvent evt) { }
public void mouseClicked(MouseEvent evt) { }
public void mouseReleased(MouseEvent evt) { }
}
Back to Lesson 25 Examples
Back to Java Main Page