import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.StringTokenizer; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; /** * A panel that contains a {@link Board} and a TextField in which the * user can enter commands. When the user presses return in the text * field (or clicks a command next to the text field), the command is * carried out. *
The command that can be of the form "add *name*", where *name* is * a valid entity name, or "*name* *direction*" where *name* is the name * of one of the entities on the board and *direction* is one of the * words up, down, left, or right. */ public class GamePanel extends JPanel { private JTextField commandInput; private Board board; /** * Create a GamePanel. * @param display The Board that will be contained in the GamePanel and to * which commands entered by the user will apply. This should not be null. */ public GamePanel(Board display) { ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent evt) { String command = commandInput.getText(); carryOutCommand(command); } }; JButton doItButton = new JButton("Do It!"); doItButton.addActionListener(listener); commandInput = new JTextField(); commandInput.addActionListener(listener); JPanel bottom = new JPanel(); bottom.setLayout(new BorderLayout()); bottom.add(new JLabel("Command: "), BorderLayout.WEST); bottom.add(commandInput, BorderLayout.CENTER); bottom.add(doItButton, BorderLayout.EAST); setLayout(new BorderLayout()); add(display, BorderLayout.CENTER); add(bottom, BorderLayout.SOUTH); board = display; } /** * Carries out a command entered by the user. * @param command the command */ private void carryOutCommand(String command) { StringTokenizer tokenizer = new StringTokenizer(command); String firstWord = tokenizer.nextToken(); Entity entity = board.getEntity(firstWord); if (firstWord.equalsIgnoreCase("add")) { String entityName = tokenizer.nextToken(); board.place(entityName, 3, 3); } else { String direction = tokenizer.nextToken(); int row = entity.getRow(); int col = entity.getColumn(); if (direction.equalsIgnoreCase("up")) row--; else if (direction.equalsIgnoreCase("down")) row++; else if (direction.equalsIgnoreCase("left")) col--; else if (direction.equalsIgnoreCase("right")) col++; entity.setPosition(row, col); } board.repaint(); commandInput.selectAll(); commandInput.requestFocus(); } }