// Scott DeRuiter 3/6/2003 // CustomButton.java // A simple "button" that reacts when pressed, implementing a // MouseListener in a Swing Applet. // 3/13/2013 Greenstein: changed from applet to JFrame import java.awt.*; import java.awt.event.*; import javax.swing.*; public class CustomButton implements MouseListener { private int xpos, ypos, buttonx, buttony, size; private boolean button1pressed; private JFrame frame; private MyPanel canvas; public CustomButton () { xpos = ypos = 0; buttonx = buttony = 30; size = 100; button1pressed = false; } public static void main(String[] args) { CustomButton cb = new CustomButton(); cb.Run(); } public void Run() { // Create a frame to hold everything frame = new JFrame ("CustomButton"); 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 MyPanel(); // create a panel to draw on canvas.setBackground(Color.lightGray); canvas.addMouseListener(this); // connects the MouseListerner to the panel window // Put frame together frame.getContentPane().add(canvas); // puts panel on frame frame.setVisible(true); } class MyPanel extends JPanel { public void paintComponent(Graphics g) { super.paintComponent(g); PlaceCircleButton ( g ); } public void PlaceCircleButton ( Graphics g ) { g.setColor ( Color.white ); g.fillOval ( buttonx - 5, buttony - 5, size + 10, size + 10 ); if ( button1pressed ) { g.setColor ( Color.red ); int choice = (int)( Math.random() * 5 + 1 ); switch ( choice ) { case 1: g.drawString ( "HEY!!!", 200, 90 ); break; case 2: g.drawString ( "YIKES????", 200, 90 ); break; case 3: g.drawString ( "Watch it, buster!", 200, 90 ); break; case 4: g.drawString ( "That Hurts!!", 200, 90 ); break; default: g.drawString ( "Try that again, buster!", 200, 90 ); break; } } else g.setColor ( Color.gray ); g.fillOval ( buttonx, buttony, size, size ); g.setColor ( Color.blue ); g.fillOval ( buttonx + 5, buttony + 5, size - 10, size - 10 ); } } public void mouseClicked ( MouseEvent e ) {} public void mousePressed ( MouseEvent e ) { xpos = e.getX(); ypos = e.getY(); if ( Math.sqrt ((xpos - 80)*(xpos - 80) + (ypos - 80)*(ypos - 80)) < 50 ) { buttonx = 33; buttony = 33; size = 100; button1pressed = true; canvas.repaint ( ); } } public void mouseReleased ( MouseEvent e ) { buttonx = 30; buttony = 30; size = 100; button1pressed = false; canvas.repaint ( ); } public void mouseEntered ( MouseEvent e ) {} public void mouseExited ( MouseEvent e ) {} }