Boggle.java Instantiate an instance of class BoggleUi, passing the reference obj
ID: 3849943 • Letter: B
Question
Boggle.java
Instantiate an instance of class BoggleUi, passing the reference object of class Board as an argument
userInterface package
Create class BoggleUi
BoggleUi.java
JFrame
JMenuBar
JMenu
JMenuItem
JMenuItem
JPanel
JButton[][]
JPanel
JScrollPane
JTextPane
JLabel
JButton
JPanel
JLabel
JButton
JLabel
Set member variable of type class Board to the parameter passed in
call method initComponents()
Set the default size of the JFrame
Set the default close operation of the JFrame
Use default layout manager BorderLayout
JMenu Boggle should be added to the JMenuBar
JMenuItems New Game and Exit should be added to the JMenu Boggle
Recommend using default Layout Manager FlowLayout
A JLabel for the current word being created
A JButton to submit the current word created
A JLabel for the player’s score
The JPanel for the Boggle board should be a 4 x 4 grid that displays a JButton for each die
Recommend using Layout Manager GridLayout
Recommend using Layout Manager BoxLayout
the JTextArea for the user to enter their words
the JScrollPane for the JTextArea to scroll as necessary
the JLabel that displays time left for the current round of play
the JButton to shake the dice
JMenuBar should be set on the JFrame
Add all the components to the JFrame
Set the visibility of the JFrame
Test Cases
Action
Expected outcome
Test Case 1
User interface displays
User interface is similar to figure 1
Test Case 2
Boggle menu
Boggle menu looks like figure 2
Test case 3
Project view
Project view matches figure 3
Boggle.java
Add to method main()Instantiate an instance of class BoggleUi, passing the reference object of class Board as an argument
userInterface package
Create class BoggleUi
BoggleUi.java
Add member variables of typeJFrame
JMenuBar
JMenu
JMenuItem
JMenuItem
JPanel
JButton[][]
JPanel
JScrollPane
JTextPane
JLabel
JButton
JPanel
JLabel
JButton
JLabel
A custom constructor should be defined that receives a parameter of type Board classSet member variable of type class Board to the parameter passed in
call method initComponents()
A method initComponents() should initialize all the components for the UI and called from the constructorSet the default size of the JFrame
Set the default close operation of the JFrame
Use default layout manager BorderLayout
Set up the JMenuBarJMenu Boggle should be added to the JMenuBar
JMenuItems New Game and Exit should be added to the JMenu Boggle
A JPanel should be created to hold the current word being created by the userRecommend using default Layout Manager FlowLayout
A JLabel for the current word being created
A JButton to submit the current word created
A JLabel for the player’s score
A JPanel should be created to hold the JButtons of diceThe JPanel for the Boggle board should be a 4 x 4 grid that displays a JButton for each die
Recommend using Layout Manager GridLayout
A JPanel should be created to holdRecommend using Layout Manager BoxLayout
the JTextArea for the user to enter their words
the JScrollPane for the JTextArea to scroll as necessary
the JLabel that displays time left for the current round of play
the JButton to shake the dice
JMenuBar should be set on the JFrame
Add all the components to the JFrame
Set the visibility of the JFrame
Boggle Boggle Boggle Board Current Word Current Word Enter Words Found Time Left 3:00 Shake Dice Score Submit Word Figure 1 Test Case 1Explanation / Answer
Boggle.java
import java.util.ArrayList;
public class Boggle {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
/**
* The main ....
*/
ArrayList dataArray;
ArrayList validWordsArray;
String dataFileName = "BoggleData.txt";
String validWordsFileName = "TemporaryDictionary.txt";
// Create an instance of class ReadDataFile, populate data and get data
ReadDataFile data = new ReadDataFile(dataFileName);
data.populateData();
dataArray = data.getData();
// Read in dictionary text file of valid words
ReadDataFile validWords = new ReadDataFile(validWordsFileName);
validWords.populateData();
validWordsArray = validWords.getData();
// Create an instance of the class board
// and pass it the file data in dataArray
Board board = new Board(dataArray);
BoggleUi ui = new BoggleUi(board, validWordsArray);
}
}
BoggleUi.java
import javax.swing.*;
import java.awt.*;
import java.awt.font.TextAttribute;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.*;
import java.text.AttributedString;
import java.util.Arrays;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class BoggleUi extends JFrame {
// Menu Components
private static JMenu gameMenu;
private static JMenuBar menuBar;
private static JMenuItem newGame;
private static JMenuItem exit;
// Button
private static JButton shakeDiceButton;
private static JButton submitWordButton;
private static JLabel timeLeftLabel;
private static JLabel currentWordLabel;
private static JLabel currentScoreLabel;
// Layout UI
private static JPanel diceLayoutPanel;
private static JPanel statusLayoutPanel;
private static JPanel currentWordPanel;
private static JTextPane wordsJPane;
private static JScrollPane scrollPane;
private Board board;
private ArrayList<Die> shakenDice;
private ArrayList validWordsArray;
private ArrayList enteredWordsArray;
private Timer timer;
/**
* Constructor
* @param board
* @param validWords
*/
public BoggleUi(Board board, ArrayList validWords) {
this.board = board;
this.validWordsArray = validWords;
initComponents();
}
/**
* Called from the constructor to initialize all UI components
* and layout the user interface
* @param
* @return
*/
private void initComponents() {
this.setTitle("Boggle Title");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setPreferredSize(new Dimension(800,620) );
this.setMinimumSize(new Dimension(800,620) );
createMenu();
setupBogglePanel();
setupWordPanel();
setupCurrentWordPanel();
this.setJMenuBar(menuBar);
this.add(diceLayoutPanel, BorderLayout.WEST);
this.add(statusLayoutPanel, BorderLayout.EAST);
this.add(currentWordPanel, BorderLayout.SOUTH);
this.setVisible(true);
}
private void createMenu() {
// Create Menu and MenuBar
menuBar = new JMenuBar();
gameMenu = new JMenu("Boggle Menu");
// Create Menu Items
newGame = new JMenuItem("New Game");
newGame.setMnemonic('N');
newGame.addActionListener(new GameListener());
exit = new JMenuItem("Exit");
exit.setMnemonic('E');
exit.addActionListener(new ExitListener());
// Add the Menu Items to the Menu
gameMenu.add(newGame);
gameMenu.add(exit);
// Add Menu to the MenuBar
menuBar.add(gameMenu);
}
private void setupBogglePanel() {
// Create the Boggle Board buttons
this.diceLayoutPanel = new JPanel(new GridLayout(4,4));
this.diceLayoutPanel.setMinimumSize(new Dimension(450,400));
this.diceLayoutPanel.setPreferredSize(new Dimension(450,400));
this.diceLayoutPanel.setBorder(BorderFactory.createTitledBorder("Boggle Board"));
this.shakenDice = board.shakeDice();
int counter = 0;
for(int row = 0; row < 4; row++)
for(int col = 0; col < 4; col++) {
JButton dieButton = new JButton();
String dieLetter = shakenDice.get(counter).getLetter();
dieButton.setText(dieLetter);
dieButton.putClientProperty("letter", dieLetter);
dieButton.putClientProperty("row", row);
dieButton.putClientProperty("col", col);
dieButton.addActionListener(new DieButtonListener() );
// die position on the board needs to be randomized
this.diceLayoutPanel.add(dieButton);
counter++;
}
}
private void setupWordPanel() {
// Set up the Layout Panel to hold the shakeDice Button
statusLayoutPanel = new JPanel();
statusLayoutPanel.setMinimumSize(new Dimension(300,400));
statusLayoutPanel.setPreferredSize(new Dimension(300,400));
statusLayoutPanel.setBorder(BorderFactory.createTitledBorder("Enter Words Found"));
// Create the wordsJPane
wordsJPane = new JTextPane();
wordsJPane.setEditable(false);
// wordsJPane.setLineWrap(true);
scrollPane = new JScrollPane(wordsJPane);
scrollPane.setPreferredSize(new Dimension(250,200));
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
wordsJPane.setMinimumSize(new Dimension(250, 200));
wordsJPane.setPreferredSize(new Dimension(250, 200));
//When startGame and timeClock is implemented it will feed the time value
timeLeftLabel = new JLabel("3:00", SwingConstants.CENTER);
timeLeftLabel.setFont(new Font("Serif", Font.PLAIN, 62));
timeLeftLabel.setMinimumSize(new Dimension(250, 150));
timeLeftLabel.setPreferredSize(new Dimension(250, 150));
timeLeftLabel.setBorder(BorderFactory.createTitledBorder("Time Left"));
// Create a shakeDice Button, enable it
shakeDiceButton = new JButton("Shake Dice");
shakeDiceButton.setEnabled(true);
shakeDiceButton.setMinimumSize( new Dimension(150, 50) );
shakeDiceButton.setPreferredSize( new Dimension(150, 50) );
shakeDiceButton.addActionListener(new GameListener());
statusLayoutPanel.add(scrollPane);
statusLayoutPanel.add(timeLeftLabel, BorderLayout.CENTER);
statusLayoutPanel.add(shakeDiceButton, BorderLayout.CENTER);
}
private void setupCurrentWordPanel() {
// Create currentWordLabel
currentWordLabel = new JLabel();
currentWordLabel.setFont(new Font("Serif", Font.PLAIN, 48));
currentWordLabel.setMinimumSize(new Dimension(300, 60));
currentWordLabel.setPreferredSize(new Dimension(300, 60));
currentWordLabel.setBorder(BorderFactory.createTitledBorder("Current Word"));
// Create submitWordButton
submitWordButton = new JButton("Submit Word");
submitWordButton.setEnabled(true);
submitWordButton.setMinimumSize( new Dimension(300, 60) );
submitWordButton.setPreferredSize( new Dimension(300, 60) );
submitWordButton.addActionListener(new GameListener());
submitWordButton.setEnabled(false);
// Create currentScoreLabel
currentScoreLabel = new JLabel("0", SwingConstants.CENTER);
currentScoreLabel.setFont(new Font("Serif", Font.PLAIN, 42));
currentScoreLabel.setMinimumSize(new Dimension(100, 60));
currentScoreLabel.setPreferredSize(new Dimension(100, 60));
currentScoreLabel.setBorder(BorderFactory.createTitledBorder("Current Score"));
// Set up the Layout Panel for currentWordPanel and add score, word and button
currentWordPanel = new JPanel();
currentWordPanel.setMinimumSize(new Dimension(100,100));
currentWordPanel.setPreferredSize(new Dimension(100,100));
currentWordPanel.setBorder(BorderFactory.createTitledBorder("Current Word"));
currentWordPanel.add(currentWordLabel);
currentWordPanel.add(submitWordButton);
currentWordPanel.add(currentScoreLabel);
}
private void shakeBogglePanel() {
this.shakenDice = board.shakeDice();
int counter = 0;
// Remove all current dice
Component[] c = this.diceLayoutPanel.getComponents();
for (int i = 0; i < c.length; i++) {
String dieLetter = this.shakenDice.get(counter).getLetter();
JButton btn = (JButton) c[i];
btn.setText(dieLetter);
btn.putClientProperty("letter", dieLetter);
btn.setEnabled(true);
}
}
private class ExitListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
int response = JOptionPane.showConfirmDialog(null, "Confirm to exit Boggle?", "Exit?", JOptionPane.YES_NO_OPTION);
if (response == JOptionPane.YES_OPTION)
System.exit(0);
}
}
private class GameListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("New Game")) {
// Clear all text
wordsJPane.setText("");
// Reset Timer to 3:00
timeLeftLabel.setText("3:00");
// Re-enable the Shake Dice Button
shakeDiceButton.setEnabled(true);
submitWordButton.setEnabled(false);
shakeBogglePanel();
currentScoreLabel.setText("0");
enteredWordsArray = new ArrayList();
currentWordLabel.setText("");
try {
timer.cancel();
} catch(Exception t) {
}
} else if (e.getActionCommand().equals("Shake Dice")) {
shakeBogglePanel();
currentScoreLabel.setText("0");
currentWordLabel.setText("");
wordsJPane.setContentType("text/plain");
wordsJPane.setText(null);
timeLeftLabel.setText("3:00");
shakeDiceButton.setEnabled(false);
submitWordButton.setEnabled(true);
enteredWordsArray = new ArrayList();
// Start a thread to keep track of the timer from 3min to 0
int delay = 1000;
int period = 1000;
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
// int counter = 180;
int counter = 30;
public void run() {
int min = counter/60;
int sec = counter%60;
if (sec < 10) {
timeLeftLabel.setText(""+min+":0"+sec);
} else {
timeLeftLabel.setText(""+min+":"+sec);
}
counter--;
if (counter < 0) {
timer.cancel();
compareComputerWords();
int gameOver = JOptionPane.showConfirmDialog(null, "Game Over!", "Exit?", JOptionPane.YES_NO_OPTION);
if (gameOver == JOptionPane.YES_OPTION)
System.exit(0);
else
// Clear all text
wordsJPane.setContentType("text/plain");
wordsJPane.setText(null);
// Reset Timer to 3:00
timeLeftLabel.setText("3:00");
// Re-enable the Shake Dice Button
shakeDiceButton.setEnabled(true);
submitWordButton.setEnabled(false);
currentWordLabel.setText("");
currentScoreLabel.setText("0");
shakeBogglePanel();
}
}
}, delay, period);
} else if (e.getActionCommand().equals("Submit Word") ) {
// Validate if the word can be used
System.out.println("Submit Word action");
if ( validateWord(currentWordLabel.getText())) {
System.out.println("Valid word found");
// Add the word in the currentWordLabel to the wordsJPane
String tempWords = wordsJPane.getText();
System.out.println(tempWords);
System.out.println(currentWordLabel.getText());
// wordsJPane.setContentType("text/plain");
wordsJPane.setText(tempWords+currentWordLabel.getText()+" ");
enteredWordsArray.add(currentWordLabel.getText());
//Update Score
int score = Integer.parseInt(currentScoreLabel.getText());
int wordLength = currentWordLabel.getText().length();
if (wordLength == 3 || wordLength == 4) {
currentScoreLabel.setText(score+1+"");
} else if (wordLength == 5) {
currentScoreLabel.setText(score+2+"");
} else if (wordLength == 6) {
currentScoreLabel.setText(score+3+"");
} else if (wordLength >= 8) {
currentScoreLabel.setText(score+11+"");
}
} else {
// word not in dictionary
System.out.println("Word not added to your list.");
}
// Clearn currentWordLabel
currentWordLabel.setText("");
}
}
}
private void compareComputerWords() {
System.out.println("Comparing Computer's Words vs Player's Words ...");
Random random = new Random();
int numPlayerWords = wordsJPane.getText().split(" ").length;
System.out.println("Total Number of Player Words: " + numPlayerWords);
int numCompWords = random.nextInt(numPlayerWords+1);
System.out.println("Total Number of Computer Words: " + numCompWords);
String[] playerWords = wordsJPane.getText().split(" ");
ArrayList cWordsArray = new ArrayList();
ArrayList pWordsArray = new ArrayList<String>(Arrays.asList(playerWords));
for (int i = 0; i < numCompWords; i++) {
// Display words computer found also
String newCompWord = pWordsArray.get(random.nextInt(numPlayerWords)).toString();
System.out.println("New Comp Word: "+newCompWord);
if (!cWordsArray.contains(newCompWord) && newCompWord!=null && newCompWord!=" ") {
cWordsArray.add(newCompWord);
// Decrease the score
int score = Integer.parseInt(currentScoreLabel.getText());
int wordLength = newCompWord.length();
if (wordLength == 3 || wordLength == 4) {
currentScoreLabel.setText(score-1+"");
} else if (wordLength == 5) {
currentScoreLabel.setText(score-2+"");
} else if (wordLength == 6) {
currentScoreLabel.setText(score-3+"");
} else if (wordLength >= 8) {
currentScoreLabel.setText(score-11+"");
}
}
}
String scoredString = new String();
// For each player word
for (int i = 0; i < pWordsArray.size(); i++) {
// If player word is also in computer word list
String s = pWordsArray.get(i).toString();
if (cWordsArray.contains(s)) {
scoredString = scoredString+"<strike>"+s+"</strike><br>";
} else {
scoredString = scoredString+s+"<br>";
}
wordsJPane.setContentType("text/html");
wordsJPane.setText(scoredString);
}
JOptionPane.showMessageDialog(null, "Comparing Computer vs Player Words "
+ "Computer Words: " + Arrays.toString(cWordsArray.toArray()));
}
private class DieButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
currentWordLabel.setText(currentWordLabel.getText() + e.getActionCommand());
JButton dieButton = (JButton) e.getSource();
dieButton.setEnabled(false);
}
}
private Boolean validateWord(String word) {
// Validate if the word can be used based on dictionary words
System.out.println("Validating Word ...");
if (validWordsArray.contains(word.toLowerCase()) ) {
System.out.println("Word is in the dictionary list.");
if (enteredWordsArray.isEmpty()) {
System.out.println("First submitted word.");
return true;
} else if(enteredWordsArray.contains(word.toLowerCase())) {
System.out.println("Word already exists in your list!");
return false;
} else {
return true;
}
} else {
return false;
}
}
}