Java Reference
In-Depth Information
public void actionPerformed(ActionEvent e)
{
panel . changeBallColor(color ) ;
} public BallColorListener(BallColor color)
{
this . color = color ;
}
}
private class SpeedMenu extends JMenu
{
public SpeedMenu () {
super ( "Ball Speed" );
for (BallSpeed s : BallSpeed . values () ) {
JMenuItem menuItem = new JMenuItem( s . name() ) ;
menuItem. addActionListener( new BallSpeedListener(s . speed())) ;
add(menuItem) ;
}
}
}
private class BallSpeedListener implements ActionListener
{
private int speed ;
public void actionPerformed(ActionEvent e)
{
panel . changeBallSpeed(speed) ;
} public BallSpeedListener( int speed)
{
this . speed = speed ;
}
}
}
The constructor of the BreakoutFrame class calls the displayMenu method to display the
menu. Let us first examine the constructor of the GameMenu class. The call super("Game")
calls the constructor of the JMenu class to set the title of the menu. When the user
clicks the Start or Pause menu item, we will call the start and pause methods of the
BreakoutPanel class, respectively. If the user selects the Quit menu item, then the code
executes System.exit(0) to terminate the program. Note that the Timer object interacts
with the ball and other shapes of the panel class, and therefore it is defined inside the panel
class. In the frame class we do not have direct access to the timer, but we can call methods
of the panel class to start and stop the timer.
Note that the code JMenuItem startGameMI = new JMenuItem("Start",
) creates
a menu item and underlines the character S . The following code creates a key accelerator.
It allows us to start the game by pressing Ctrl+S from the keyboard.
startGameMI . setAccelerator (KeyStroke . getKeyStroke (KeyEvent .VK S,
InputEvent .CTRL MASK) )
'
S
'
Next, let us examine the ColorMenu class. Since BallColor is an enum type, we can
use the syntax BallColor.values() to get all the possible values of the type. The code
color.name() gives us the name that is associated with the color in the enum type. In our
case, we will have the menu items: Red Ball , Blue Ball ,and Green Ball . The constructor
of the color listener simply saves the color. When one of the color menu items is selected,
then the changeBallColor method is called for the panel. Since the ball is inside the panel
class, we cannot directly change the color of the ball.
 
Search WWH ::




Custom Search