import javax.swing.JApplet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.geom.Line2D; import javax.swing.JPanel; import javax.swing.JFrame; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; /** * Class ButtonDemo - write a description of the class here * * @author John Paxton * @version January 30, 2004 */ public class ButtonDemo extends JApplet { /** * init method for applet. */ public void init() { JPanel panel = new JPanel(); // the button panel JFrame frame = new JFrame(); // the button frame panel.add(makeButton("North", 0, -10)); panel.add(makeButton("South", 0, 10)); panel.add(makeButton("East", 10, 0)); panel.add(makeButton("West", -10, 0)); frame.setContentPane(panel); frame.pack(); frame.show(); x = getWidth() / 2; y = getHeight() / 2; } /** * This method enables a button to be created * * @param label A string indicating the label of the button. * @param xInc An int that shows how to change the x-coordinate of the cursor. * @param yInc An int that shows how to change the y-coordinate of the cursor. * * @return A JButton that is the button created. */ private JButton makeButton (String label, final int xInc, final int yInc) { JButton button = new JButton(label); // the new button class myButtonListener implements ActionListener { public void actionPerformed (ActionEvent e) { if ( ((x + xInc) >= SIZE) && ((x + xInc) <= getWidth() - SIZE) ) { x += xInc; } if ( ((y+ yInc) >= SIZE) && ((y + yInc) <= getHeight() - SIZE) ) { y += yInc; } repaint(); } } button.addActionListener (new myButtonListener()); return button; } /** * Paint method for applet. * * @param g the Graphics object for this applet */ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; // the Graphics2D context int distance = SIZE / 2; // the distance from the center of the cursor g2.draw(new Line2D.Double(x-distance, y, x+distance, y)); g2.draw(new Line2D.Double (x, y-distance, x, y+distance)); } private int x; // x coordinate of center of cursor private int y; // y coordinate of center of cursor private static final int SIZE = 10; // height and width of cursor }