This is a sample program that I intend to post as part of a series of beginner level Java tutorials. Please provide any feedback on improvements that would make example more clear or illustrate/emphasize best practices. The example drawns a ball object to a panel on a mouse click and then moves it randomly with another mouse click.
Class BouncingBall
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/*
* this class will add a red ball to a canvas or play area, when a button is clicked and
* then move about randomly when another button is clicked
*
* jmergenthaler 10/1/2011
*/
public class BouncingBall {
private JFrame frame = new JFrame();
private JPanel actionPanel = new JPanel();
private JPanel playarea = new JPanel();
private JButton btnNew = new JButton("Add Red Ball");
private JButton movebtn = new JButton("Move it");
//constructor
BouncingBall(){
buildTheGUI();
}
public void buildTheGUI(){
frame.setLayout( new BorderLayout());
btnNew.addActionListener( new ButtonClickHandler() );
movebtn.addActionListener( new MoveButtonClickHandler() );
actionPanel.add(btnNew);
actionPanel.add(movebtn);
frame.add(BorderLayout.NORTH,actionPanel);
frame.add(BorderLayout.SOUTH,playarea);
frame.setSize(500, 500);
frame.setVisible(true);
}
public static void main(String args[]){
new BouncingBall();
}
class ButtonClickHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//create initial Ball object add to the frame
frame.add(new Ball() );
//draw
frame.validate();
}
}
class MoveButtonClickHandler implements ActionListener{
public void actionPerformed(ActionEvent e){
//polymorphic behavior, calling the Ball constructor differently
frame.add(new Ball(1) );
//redraw
frame.validate();
}
}// end class MoveButtonClickHandler
}//end class BouncingBall
class 2 - the Ball class
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JPanel;
class Ball extends JPanel{
//private instance variables avail. only avail to methods in this class
private int x,y,w,h;
//constructor
Ball(){
this.x = 200;
this.y = 200;
this.w = 100;
this.h = 100;
}
//constructor with different behavior
Ball(int a){
Random rand = new Random();
this.w = 100;
this.h = 100;
this.x = rand.nextInt(300);
this.y = rand.nextInt(300);
}
//draw the ball
//@override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(x, y, h, w);
}
}//end class Ball