Java Reference
In-Depth Information
up
down
left
right
Figure 14.2 The layout of the GUI for the block puzzle
configuration on all positions ( r
c ), ( r is the row number, c is the column number)
to find the block number at this position. The blocks are drawn as rectangles with
a number near the middle. The missing block is shown as a filled black rectangle.
The code for drawing a block and the empty place is put into two private methods.
Putting it into paintComponent is of course possible, but would make the structure
hard to follow. The drawing is scalable (resizeable). We use the technique described
in Section 13.3 for this purpose.
The panel does not know anything about the rules of the game, it can merely
display the current state. Therefore, method makeMove(move) makes a move by
calling the method moveIt(move) of the board model. The panel's display has to
be updated if the configuration is changed. This update is made by calling the
panel's repaint method. If the move has not been made a warning message is
displayed. It uses a predefined message dialogue from class JOptionPane .
The class has a public method getBlockNoAtPixels(x,y) which will be used
in the control part. It determines the number of the block that contains the pixel
coordinates ( x
,
y ). In order to find out which row of blocks contains the given
pixel y -coordinate we first divide the height of the panel by the number of rows.
This is the height of a single row in pixels. Then we divide y by this height to
get the row number. Note that all numbers involved are integers; then rounding
is downwards and the correct row number is computed. The column number is
computed analogously.
,
File: its/BlockPuzzle/BlockPuzzlePanel.java
1. package its.BlockPuzzle;
2.
3. import java.awt.Color;
4. import java.awt.Dimension;
5. import java.awt.Graphics;
6. import javax.swing.JPanel;
Search WWH ::




Custom Search