//------------------------------------------------------------------------------------------------- // // MovingGraphicsComponent.java // // written by: Simon Parsons // last modified: 30th July 2012 // // An object that draws an ellipse moves its position on the screen. based on // the examples from "Learning Java" by Niemeyer and Knudsen, page 49-51 and // page 694. import java.awt.*; // Use the awt library import java.awt.event.*; import java.awt.geom.*; import javax.swing.*; // Use the swing library // The Moving Component class is a subclass of JComponent and defines an object that listens // for actions (in this case a button press). public class MovingGraphicsComponent extends JComponent implements ActionListener { int elX = 25, elY = 95; // Ellipse coordinates JButton theButton; // A button object public MovingGraphicsComponent() { theButton = new JButton("Press me!"); // Create button, set the layout setLayout(new FlowLayout()); // type and then add the button. add(theButton); theButton.addActionListener(this); // Get ready for button presses } public void paintComponent(Graphics g){ // Draw an ellipse at a specific Graphics2D g2 = (Graphics2D)g; Shape c = new Ellipse2D.Float(elX, elY, 250, 150); // location within the frame. g2.setPaint(Color.blue); g2.fill(c); } public void actionPerformed(ActionEvent e){ // If the button is pressed, move the message if(e.getSource() == theButton){ elX+=10; elY+=10; repaint(); } } }