// ButtonFun Demo import java.applet.Applet; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; /** This applet lets the user move a rectangle by clicking on buttons labeled "Left", "Right", "Up", and "Down". */ public class ButtonFun extends Applet { private Rectangle box; private static final int BOX_X = 100; private static final int BOX_Y = 100; private static final int BOX_WIDTH = 20; private static final int BOX_HEIGHT = 30; public ButtonFun() { // the rectangle that the paint method draws box = new Rectangle(BOX_X, BOX_Y, BOX_WIDTH, BOX_HEIGHT); // the panel for holding the user interface components JPanel panel = new JPanel(); panel.add(makeButton("Left", -BOX_WIDTH, 0)); panel.add(makeButton("Right", BOX_WIDTH, 0)); panel.add(makeButton("Up", 0, -BOX_HEIGHT)); panel.add(makeButton("Down", 0, BOX_HEIGHT)); // the frame for holding the component panel JFrame frame = new JFrame(); frame.setContentPane(panel); frame.pack(); frame.show(); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.draw(box); } /** Makes a button that moves the box. @param label the label to show on the button @param dx the amount by which to move the box in x-direction when the button is clicked @param dy the amount by which to move the box in y-direction when the button is clicked @return the button */ public JButton makeButton(String label, final int dx, final int dy) { JButton button = new JButton(label); class ButtonListener implements ActionListener { public void actionPerformed(ActionEvent event) { box.translate(dx, dy); repaint(); } }; ButtonListener listener = new ButtonListener(); button.addActionListener(listener); return button; } }