Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 7 ■ WRITING A USER INTERFACE

if (mineCount == 3) return threeIcon;
if (mineCount == 4) return fourIcon;
if (mineCount == 5) return fiveIcon;
if (mineCount == 6) return sixIcon;
if (mineCount == 7) return sevenIcon;
if (mineCount == 8) return eightIcon;
return null;
}
}


Notice that every member, both fields and methods, is static. We do that because there's no point in
loading the icon images more than once. Because being static is handy for the icons, we also make the
methods static. Consequently, we never need to create an instance of the MineIcon class. To get an icon,
we can use the syntax for calling a class method. (Remember that a class method belongs to the class,
not to any instance of the class.) That syntax is the name of the class, a period, and the name and
arguments of the method, such as MineIcon.getMineIcon();.
Static methods are fairly common. You can use them for any task that doesn't require an instance of
the containing class. Even classes that consist entirely of static methods are fairly common. As with the
MineIcon class, they provide functionality that doesn't need an object of any sort to work. They either
offer utility methods (such as formatting String objects in special ways needed by a particular
application) or return items (such as our icons) that don't require any other input to find. It might seem
odd, because you've never seen it before, but it gives you another tool in your programming toolkit.
Hang in there. We're almost done with the code for the MineSweeper program. We have just the two
classes that listen for user actions (mouse clicks and menu actions) left to go. Let's keep going with the
MineSweeperMouseListener class, shown in Listing 7-28.


Listing 7-28. The MineSweeperMouseListener class


package com.apress.java7forabsolutebeginners.examples.MineSweeper;


import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;


import javax.swing.JButton;


public class MineSweeperMouseListener implements MouseListener {


private MineSweeper mineSweeper;
private MineSweeperHelper mineSweeperHelper;


public MineSweeperMouseListener(MineSweeper mineSweeper, MineSweeperHelper helper) {
this.mineSweeper = mineSweeper;
mineSweeperHelper = helper;
}


@Override
public void mouseClicked(MouseEvent e) {
}

Free download pdf