Numbering A Crossword Java ACM Graphics - java

The problem asks for an acm graphics program that reads a txt file like this:
R
FUN
SALES
RECEIPT
MERE#FARM
DOVE###RAIL
MORE#####DRAW
HARD###TIED
LION#SAND
EVENING
EVADE
ARE
D
and makes a crossword puzzle, with blank squares on letters, black squares on '#', and nothing on empty spaces. The problem also asks that "if the square is at the beginning of a word running across, down, or both, the square should contain a number that is assigned sequentially through the puzzle."
I have the square drawing working, but I'm stuck on drawing the numbers correctly. There is something wrong with how I'm detecting null space and black squares. Can someone tell me what I'm doing wrong, please?
Here is the code:
import acm.program.*;
import java.io.*;
import java.util.*;
import acm.graphics.*;
import java.awt.*;
public class Crossword extends GraphicsProgram {
public void run() {
String fileName = "crosswordfile.txt";
makeCrosswordPuzzle(fileName);
}
private static final int sqCon = 15; // constant for square x and y dimensions
private int y = 0;
public void makeCrosswordPuzzle(String fileName) {
BufferedReader rd;
int y = 0; // y value for the square being added during that loop. increments by sqCon after every line
int wordNumber = 1; // variable for numbers added to certain boxes. increments every time the program adds a number
try {
rd = new BufferedReader(new FileReader(fileName));
String line = rd.readLine(); //reads one line of the text document at a time and makes it a string
while (line != null) {
int x = 0;
for (int i = 0; i < line.length(); i++) {
char lineChar = line.charAt(i);// the character being examined for each loop
GRect whiteSq = new GRect(sqCon,sqCon); //GRect for blank squares
GRect blackSq = new GRect(sqCon,sqCon);//GRect for black squares
blackSq.setFilled(true);
blackSq.setFillColor(Color.BLACK);
if (lineChar == '#'){
add (blackSq,x,y);
}
if (Character.isLetter(lineChar)) {
add (whiteSq, x, y);
// if the element above or to the left of the current focus is null or blackSq, place the number and then increment wordNumber
GObject above = getElementAt(x+sqCon/2,y-sqCon/2);
GObject left = getElementAt(x-sqCon/2, y+sqCon/2);
GLabel wordNumberLabel = new GLabel(Integer.toString(wordNumber));
if (above == null || left == null || above == blackSq || left == blackSq) {
add(wordNumberLabel,x,y+sqCon);
wordNumber++;
}
}
x += sqCon;
}
line = rd.readLine();
y += sqCon;
}
rd.close();
}
catch (IOException e) {
throw new ErrorException(e);
}
}
}
Edited to add:
I copied your code over to my Eclipse and ran it. Here's the result.
You did fine on the upper half, but you missed the down numbers on the lower half.
Here's the same code, reformatted so it's easier to read.
import java.awt.Color;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import acm.graphics.GLabel;
import acm.graphics.GObject;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
import acm.util.ErrorException;
public class Crossword extends GraphicsProgram {
private static final long serialVersionUID = -7971434624427958742L;
public void run() {
// String fileName = "crosswordfile.txt";
String fileName = "C:/Eclipse/eclipse-4.2-work/com.ggl.testing/crosswordfile.txt";
makeCrosswordPuzzle(fileName);
}
private static final int sqCon = 15; // constant for square x and y
// dimensions
private int y = 0;
public void makeCrosswordPuzzle(String fileName) {
BufferedReader rd;
int y = 0; // y value for the square being added during that loop.
// increments by sqCon after every line
int wordNumber = 1; // variable for numbers added to certain boxes.
// increments every time the program adds a number
try {
rd = new BufferedReader(new FileReader(fileName));
String line = rd.readLine(); // reads one line of the text document
// at a time and makes it a string
while (line != null) {
int x = 0;
for (int i = 0; i < line.length(); i++) {
char lineChar = line.charAt(i);// the character being
// examined for each loop
GRect whiteSq = new GRect(sqCon, sqCon); // GRect for blank
// squares
GRect blackSq = new GRect(sqCon, sqCon);// GRect for black
// squares
blackSq.setFilled(true);
blackSq.setFillColor(Color.BLACK);
if (lineChar == '#') {
add(blackSq, x, y);
}
if (Character.isLetter(lineChar)) {
add(whiteSq, x, y);
// if the element above or to the left of the current
// focus is null or blackSq, place the number and then
// increment wordNumber
GObject above = getElementAt(x + sqCon / 2, y - sqCon
/ 2);
GObject left = getElementAt(x - sqCon / 2, y + sqCon
/ 2);
GLabel wordNumberLabel = new GLabel(
Integer.toString(wordNumber));
if (above == null || left == null || above == blackSq
|| left == blackSq) {
add(wordNumberLabel, x, y + sqCon);
wordNumber++;
}
}
x += sqCon;
}
line = rd.readLine();
y += sqCon;
}
rd.close();
} catch (IOException e) {
throw new ErrorException(e);
}
}
}

I followed the advice of my own comment. I created the crossword puzzle answer, numbered the crossword puzzle answer, and finally drew the crossword puzzle answer.
Here's the applet result:
I kept a List of crossword puzzle cells. That way, I could determine the length and the width of the puzzle by the number of characters on a row and the number of rows of the input text file. I didn't have to hard code the dimensions.
For each crossword cell, I kept track of whether or not it was a letter, and whether or not it was a dark space.
When determining where to put the numbers, I followed 2 rules.
An across number is placed where the cell left of the cell is empty or dark, and there are three or more letters across.
A down number is placed where the cell above the cell is empty or dark, there are three or more letters down, and there is no across number.
You can see in the code that I had to do some debug printing to get the crossword puzzle clue numbering correct. I broke the process into many methods to keep each method as simple as possible.
Finally, I drew the crossword puzzle answer from the information in the List.
Here's the code:
import java.awt.Color;
import java.awt.Point;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import acm.graphics.GLabel;
import acm.graphics.GRect;
import acm.program.GraphicsProgram;
import acm.util.ErrorException;
public class Crossword extends GraphicsProgram {
private static final boolean DEBUG = false;
private static final long serialVersionUID = -7971434624427958742L;
private List<CrosswordCell> crosswordCellList;
#Override
public void run() {
this.crosswordCellList = new ArrayList<CrosswordCell>();
// String fileName = "crosswordfile.txt";
String fileName = "C:/Eclipse/eclipse-4.2-work/" +
"com.ggl.testing/crosswordfile.txt";
try {
readCrosswordAnswer(fileName);
if (DEBUG) printCrosswordAnswer();
numberCrosswordCells();
if (DEBUG) printCrosswordAnswer();
drawCrosswordAnswer();
} catch (FileNotFoundException e) {
throw new ErrorException(e);
} catch (IOException e) {
throw new ErrorException(e);
}
}
private void readCrosswordAnswer(String fileName)
throws FileNotFoundException, IOException {
BufferedReader reader =
new BufferedReader(new FileReader(fileName));
String line = "";
int row = 0;
while ((line = reader.readLine()) != null) {
for (int column = 0; column < line.length(); column++) {
CrosswordCell cell = new CrosswordCell(column, row);
char lineChar = line.charAt(column);
if (lineChar == '#') {
cell.setDarkCell(true);
} else if (Character.isLetter(lineChar)) {
cell.setLetter(true);
}
crosswordCellList.add(cell);
}
row++;
}
reader.close();
}
public void printCrosswordAnswer() {
for (CrosswordCell cell : crosswordCellList) {
System.out.println(cell);
}
}
private void numberCrosswordCells() {
int clueNumber = 1;
for (CrosswordCell cell : crosswordCellList) {
if (cell.isLetter()) {
clueNumber = testCell(cell, clueNumber);
}
}
}
private int testCell(CrosswordCell cell, int clueNumber) {
Point p = cell.getLocation();
CrosswordCell leftCell = getLeftCell(p.x, p.y);
List<CrosswordCell> acrossList = getRightCells(p.x, p.y);
if (DEBUG) {
System.out.print(p);
System.out.println(", " + leftCell + " " +
acrossList.size());
}
if ((leftCell == null) && (acrossList.size() >= 3)) {
cell.setClueNumber(clueNumber++);
} else {
CrosswordCell aboveCell = getAboveCell(p.x, p.y);
List<CrosswordCell> downList = getBelowCells(p.x, p.y);
if (DEBUG) {
System.out.print(p);
System.out.println(", " + aboveCell + " " +
downList.size());
}
if ((aboveCell == null) && (downList.size() >= 3)) {
cell.setClueNumber(clueNumber++);
}
}
return clueNumber;
}
private CrosswordCell getAboveCell(int x, int y) {
int yy = y - 1;
return getCell(x, yy);
}
private CrosswordCell getLeftCell(int x, int y) {
int xx = x - 1;
return getCell(xx, y);
}
private List<CrosswordCell> getBelowCells(int x, int y) {
List<CrosswordCell> list = new ArrayList<CrosswordCell>();
for (int i = y; i < (y + 3); i++) {
CrosswordCell cell = getCell(x, i);
if (cell != null) {
list.add(cell);
}
}
return list;
}
private List<CrosswordCell> getRightCells(int x, int y) {
List<CrosswordCell> list = new ArrayList<CrosswordCell>();
for (int i = x; i < (x + 3); i++) {
CrosswordCell cell = getCell(i, y);
if (cell != null) {
list.add(cell);
}
}
return list;
}
private CrosswordCell getCell(int x, int y) {
for (CrosswordCell cell : crosswordCellList) {
Point p = cell.getLocation();
if ((p.x == x) && (p.y == y)) {
if (cell.isDarkCell()) {
return null;
} else if (cell.isLetter()){
return cell;
} else {
return null;
}
}
}
return null;
}
private void drawCrosswordAnswer() {
int sqCon = 32;
for (CrosswordCell cell : crosswordCellList) {
Point p = cell.getLocation();
if (cell.isDarkCell()) {
drawDarkCell(p, sqCon);
} else if (cell.isLetter()) {
drawLetterCell(cell, p, sqCon);
}
}
}
private void drawDarkCell(Point p, int sqCon) {
GRect blackSq = new GRect(sqCon, sqCon);
blackSq.setFilled(true);
blackSq.setFillColor(Color.BLACK);
add(blackSq, p.x * sqCon, p.y * sqCon);
}
private void drawLetterCell(CrosswordCell cell, Point p, int sqCon) {
GRect whiteSq = new GRect(sqCon, sqCon);
add(whiteSq, p.x * sqCon, p.y * sqCon);
if (cell.getClueNumber() > 0) {
String label = Integer.toString(cell.getClueNumber());
GLabel wordNumberLabel = new GLabel(label);
add(wordNumberLabel, p.x * sqCon + 2, p.y * sqCon + 14);
}
}
class CrosswordCell {
private boolean darkCell;
private boolean isLetter;
private int clueNumber;
private Point location;
public CrosswordCell(int x, int y) {
this.location = new Point(x, y);
this.clueNumber = 0;
this.darkCell = false;
this.isLetter = false;
}
public boolean isDarkCell() {
return darkCell;
}
public void setDarkCell(boolean darkCell) {
this.darkCell = darkCell;
}
public boolean isLetter() {
return isLetter;
}
public void setLetter(boolean isLetter) {
this.isLetter = isLetter;
}
public int getClueNumber() {
return clueNumber;
}
public void setClueNumber(int clueNumber) {
this.clueNumber = clueNumber;
}
public Point getLocation() {
return location;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("CrosswordCell [location=");
builder.append(location);
builder.append(", clueNumber=");
builder.append(clueNumber);
builder.append(", darkCell=");
builder.append(darkCell);
builder.append(", isLetter=");
builder.append(isLetter);
builder.append("]");
return builder.toString();
}
}
}

Related

Java Sockets - Unable to enter second input on client side [EDIT]

I am trying to make a Connect 5 game, where the game logic is held on the server side, with the client side influencing the current game state. So far, I have the game logic implemented and it works just fine if you were to run it. I am running into issues when trying to implement the actual client/server sider of things.
I am not exactly sure how to go about doing it. What I can do at the moment is get the player names and the size of the board. When it comes to actually playing the game, I run into some issues such as keeping the game running and getting the player's move. Currently the server will stop running after a short period of time. I have tried using a while(true) to keep it running but it doesn't seem to work.
Another issue is displaying the actual board on the client side - while I am able to display the board if you were to just play the game from the server class using System.out.println(fiveInARow);, which displays the board after every move. I have tried using How to send String array Object over Socket? to display the board (testing if I can even just get the empty board at the start of the game to display on the client side), I get an error.
Should I be doing something like How to get input from Console in Java Client Server Program to get an input from the user inside the for (int player = 0; moves-- > 0; player = 1 - player)?
UPDATED: So I'm able to make a move and the move will be played accordingly. However, the second player is unable to make a move (unable to enter input on client side after first input).
Server
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
class FiveInARow implements Runnable {
private ArrayList<String> playerNames = new ArrayList<String>();
private String currPlayer;
private Socket socket;
private Scanner scanner;
private int width, height;
private static final char[] PLAYERS = { 'X', 'O' };
private char[][] gameBoard;
private int lastCol = -1, lastRow = -1;
public FiveInARow(Socket socket) {
this.socket = socket;
}
/**
*
* #param w - Width
* #param h - Height
* #param p1 - Player 1
* #param p2 - Player 2
*/
public FiveInARow(int w, int h, String p1, String p2) {
width = w;
height = h;
gameBoard = new char[h][];
playerNames.add(p1);
playerNames.add(p2);
for (int i = 0; i < h; i++) {
Arrays.fill(gameBoard[i] = new char[w], '.');
}
}
// Display the game board
public String toString() {
return IntStream.range(0, width).mapToObj(Integer::toString).collect(Collectors.joining("")) + "\n"
+ Arrays.stream(gameBoard).map(String::new).collect(Collectors.joining("\n"));
}
// Get string representation of the row containing the last play of the user
public String horizontal() {
return new String(gameBoard[lastRow]);
}
// Get string representation of the column containing the last play of the user
public String vertical() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
stringBuilder.append(gameBoard[h][lastCol]);
}
return stringBuilder.toString();
}
// Get string representation of the "/" diagonal containing the last play of the
// user
public String fowardSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol + lastRow - h;
if (w >= 0 && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
/**
* Get string representation of the "\" diagonal containing the last play of the
* user
*
* #return
*/
public String backSlashDiagonal() {
StringBuilder stringBuilder = new StringBuilder(height);
for (int h = 0; h < height; h++) {
int w = lastCol - lastRow + h;
if (0 <= w && w < width) {
stringBuilder.append(gameBoard[h][w]);
}
}
return stringBuilder.toString();
}
public static boolean contains(String str, String subString) {
return str.indexOf(subString) >= 0;
}
// Determine if a game as been won
public boolean hasWon() {
if (lastCol == -1) {
System.err.println("No move has been made yet");
return false;
}
char symbol = gameBoard[lastRow][lastCol];
String streak = String.format("%c%c%c%c%c", symbol, symbol, symbol, symbol, symbol);
return contains(horizontal(), streak) || contains(vertical(), streak) || contains(fowardSlashDiagonal(), streak)
|| contains(backSlashDiagonal(), streak);
}
/**
*
* #param symbol - Symbol/piece to be played
* #param scanner - Input
*/
public void playMove(char symbol, Scanner scanner) {
do {
if (symbol == PLAYERS[0]) {
currPlayer = playerNames.get(0);
} else {
currPlayer = playerNames.get(1);
}
System.out.println("\n" + currPlayer + "'s turn: ");
int col = scanner.nextInt();
// Check if input is valid
if (!(0 <= col && col < width)) {
System.out.println("Column must be between 0 and " + (width - 1));
continue;
}
for (int h = height - 1; h >= 0; h--) {
if (gameBoard[h][col] == '.') {
gameBoard[lastRow = h][lastCol = col] = symbol;
return;
}
}
// If column has already been filled, we need to ask for a new input
System.out.println("Column " + col + " is full");
} while (true);
}
// public static void main(String[] args) {
// try (Scanner input = new Scanner(System.in)) {
// String player1Name, player2Name;
// int height = 6;
// int width = 9;
// int moves = height * width;
//
// System.out.println("Player 1 name: ");
// player1Name = input.next();
//
// System.out.println("Player 2 name: ");
// player2Name = input.next();
//
// FiveInARow fiveInARow = new FiveInARow(width, height, player1Name, player2Name);
//
// System.out.println("Enter 0 - " + (width - 1) + " to play a piece\n");
//
// System.out.println(fiveInARow);
//
// for (int player = 0; moves-- > 0; player = 1 - player) {
// char symbol = PLAYERS[player];
//
// fiveInARow.playMove(symbol, input);
//
// System.out.println(fiveInARow);
//
// if (fiveInARow.hasWon()) {
// System.out.println("\nPlayer " + symbol + " wins!");
//
// return;
// }
// }
//
// System.out.println("Game over. Draw game!");
// }
// }
#Override
public void run() {
int height = 6;
int width = 9;
int moves = height * width;
System.out.println("Connected: " + socket);
try {
FiveInARow fiveInARow = new FiveInARow(width, height, "Kevin", "Fasha");
Scanner scanner = new Scanner(socket.getInputStream());
PrintWriter printWriter = new PrintWriter(socket.getOutputStream(), true);
// while (scanner.hasNextInt()) {
// printWriter.println(scanner.nextInt());
// }
System.out.println(fiveInARow);
// while (scanner.hasNextInt()) {
for (int player = 0; moves-- > 0; player = 1 - player) {
char symbol = PLAYERS[player];
fiveInARow.playMove(symbol, scanner);
System.out.println(fiveInARow);
if (fiveInARow.hasWon()) {
System.out.println("\nPlayer " + symbol + " wins!");
return;
}
// }
}
} catch (Exception exception) {
System.out.println("Error: " + socket);
} finally {
try {
socket.close();
} catch (IOException e) {
}
System.out.println("Closed: " + socket);
}
}
public static void main(String[] args) throws Exception {
try (ServerSocket serverSocket = new ServerSocket(59898)) {
System.out.println("The game server is running...");
ExecutorService pool = Executors.newFixedThreadPool(20);
while (true) {
pool.execute(new FiveInARow(serverSocket.accept()));
}
}
}
}
Client
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public class FiveInARowClient {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Pass the server IP as the sole command line argument");
return;
}
try (Socket socket = new Socket(args[0], 59898)) {
System.out.println("Enter lines of text then Ctrl+D or Ctrl+C to quit");
Scanner scanner = new Scanner(System.in);
Scanner in = new Scanner(socket.getInputStream());
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while (scanner.hasNextLine()) {
out.println(scanner.nextLine());
System.out.println(in.nextLine());
}
}
}
}

Android - An algorithm to check recursively if a map is solvable

I am making an android Hashikawekero puzzle game, I have implemented a algorithm to spawn nodes (Islands) at random positions using a 2-d array this works fine it creates the node at random position but most of the times the map cant be solved. The map nodes spawn at random.
BoardCreation.java Class - this generates the map.
package Island_and_Bridges.Hashi;
import android.annotation.TargetApi;
import android.os.Build;
import android.util.Log;
import java.util.Random;
import static junit.framework.Assert.*;
//This class Creates the map by random using a 2d array
public class BoardCreation {
// This class member is used for random initialization purposes.
static private final Random random = new Random();
// The difficulty levels.
private static final int EASY = 0;
static public final int MEDIUM = 1;
static public final int HARD = 2;
static public final int EMPTY = 0;
private static int ConnectionFingerprint(BoardElement start, BoardElement end) {
int x = start.row * 100 + start.col;
int y = end.row * 100 + end.col;
// Swap to get always the same fingerprint independent whether we are called
// start-end or end-start
if (x > y ) {
int temp = x;
x = y;
y = temp;
}
Log.d("", String.format("%d %d" , x ,y));
return x ^ y;
}
public class State {
// The elements of the board are stored in this array.
// A value defined by "EMPTY" means that its not set yet.
public BoardElement [][] board_elements = null;
public int [][] cell_occupied = null;
// The width of the board. We only assume squared boards.
public int board_width=0;
public State(int width) {
board_width = width;
board_elements = new BoardElement[width][width];
cell_occupied = new int[width][width];
}
public State CloneWithoutConnections() {
State newstate = new State(board_width);
if (board_elements != null) {
newstate.board_elements = new BoardElement[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
for (int j = 0; j < board_elements.length; ++j) {
if (board_elements[i][j] == null)
continue;
newstate.board_elements[i][j] = board_elements[i][j].clone();
}
}
}
if (cell_occupied != null) {
assert board_elements != null;
newstate.cell_occupied = new int[board_elements.length][board_elements.length];
for (int i = 0; i < board_elements.length; ++i) {
System.arraycopy(cell_occupied[i], 0, newstate.cell_occupied[i], 0, board_elements.length);
}
}
return newstate;
}
public void AddToBridgeCache(BoardElement first, BoardElement second) {
if (first == null || second == null) { return; }
final int fingerprint = ConnectionFingerprint(first, second);
Log.d(getClass().getName(),
String.format("Fingerprint of this bridge %d", fingerprint));
// mark the end points as occupied.
cell_occupied[first.row][first.col] = fingerprint;
cell_occupied[second.row][second.col] = fingerprint;
int dcol = second.col - first.col;
int drow = second.row - first.row;
if (first.row == second.row) {
for (int i = (int) (first.col + Math.signum(dcol)); i != second.col; i += Math.signum(dcol)) {
cell_occupied[first.row][i] = fingerprint;
String.format("deleting bridge");
}
} else {
assert first.col == second.col;
for (int i = (int) (first.row + Math.signum(drow)); i != second.row; i+= Math.signum(drow)) {
cell_occupied[i][first.col] = fingerprint;
}
}
}
} // end of state
private State current_state, old_state;
static private final int WIDTH_EASY = 7;
private void NewGame(int hardness) {
switch(hardness) {
case EASY:
Log.d(getClass().getName(), "Initializing new easy game");
InitializeEasy();
old_state = getCurrentState().CloneWithoutConnections();
break;
}
}
public void ResetGame() {
if (old_state != null) {
Log.d(getClass().getName(), "Setting board_elements to old_elements");
setCurrentState(old_state.CloneWithoutConnections());
} else {
Log.d(getClass().getName(), "old_lements are zero");
}
}
public BoardCreation(int hardness) {
NewGame(hardness);
}
public boolean TryAddNewBridge(BoardElement start, BoardElement end, int count) {
assertEquals(count, 1);
assert (start != null);
assert (end != null);
final int fingerprint = ConnectionFingerprint(start, end);
Log.d(getClass().getName(),
String.format("considering (%d,%d) and (%d,%d)", start.row,start.col, end.row,end.col));
if (start.row == end.row && start.col == end.col) {
Log.d(getClass().getName(), "Same nodes selected!");
return false;
}
assert count > 0;
int dcol = end.col - start.col;
int drow = end.row - start.row;
// It must be a vertical or horizontal bridge:
if (Math.abs(dcol) > 0 && Math.abs(drow) > 0) {
Log.d(getClass().getName(), "not a horizontal or vertical bridge.");
return false;
}
// First we check whether start and end elements can take the specified bridge counts.
int count_start = start.GetCurrentCount();
int count_end = end.GetCurrentCount();
if (count_start + count > start.max_connecting_bridges ||
count_end + count > end.max_connecting_bridges) {
Log.d(getClass().getName(), "This Bridge is not allowed");
return false;
}
Log.d(getClass().getName(),
String.format("Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row, start.col,
count_end, end.row, end.col));
Connection start_connection = null;
Connection end_connection = null;
// Next we check whether we are crossing any lines.
if (start.row == end.row) {
for (int i = (int) (start.col + Math.signum(dcol)); i != end.col; i += Math.signum(dcol)) {
if (getCurrentState().cell_occupied[start.row][i] > 0 &&
getCurrentState().cell_occupied[start.row][i] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
assert start.col != end.col;
if (start.col > end.col) {
start.connecting_east = GetOrCreateConnection(end, start.connecting_east);
end.connecting_west = GetOrCreateConnection(start, end.connecting_west);
start_connection = start.connecting_east;
end_connection = end.connecting_west;
} else {
start.connecting_west = GetOrCreateConnection(end, start.connecting_west);
end.connecting_east = GetOrCreateConnection(start, end.connecting_east);
start_connection = start.connecting_west;
end_connection = end.connecting_east;
}
} else {
assert start.col == end.col;
for (int i = (int) (start.row + Math.signum(drow)); i != end.row ; i += Math.signum(drow)) {
if (getCurrentState().cell_occupied[i][start.col] > 0 &&
getCurrentState().cell_occupied[i][start.col] != fingerprint) {
Log.d(getClass().getName(), "Crossing an occupied cell.");
return false;
}
}
if (start.row > end.row ) {
start.connecting_north = GetOrCreateConnection(end, start.connecting_north);
end.connecting_south = GetOrCreateConnection(start, end.connecting_south);
start_connection = start.connecting_north;
end_connection = end.connecting_south;
} else {
start.connecting_south= GetOrCreateConnection(end, start.connecting_south);
end.connecting_north = GetOrCreateConnection(start, end.connecting_north);
start_connection = start.connecting_south;
end_connection = end.connecting_north;
}
}
start_connection.destination = end;
end_connection.destination = start;
start_connection.second += count;
end_connection.second += count;
getCurrentState().AddToBridgeCache(start, end);
Log.d(getClass().getName(),
String.format("New bridge added. Sums:%d # (%d,%d) and %d # (%d,%d)",
count_start, start.row,start.col,
count_end, end.row,end.col));
return true;
}
private Connection GetOrCreateConnection(
BoardElement end,
Connection connection) {
if (connection!= null) { return connection; }
return new Connection();
}
#TargetApi(Build.VERSION_CODES.N)
private void InitializeEasy() {
Random rand = new Random();
String[][] debug_board_state = new String[7][7];
setCurrentState(new State(WIDTH_EASY));
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
debug_board_state[row][column] = String.valueOf(rand.nextInt(5));
}
}
for (int row = 0; row < debug_board_state.length; row++) {
for (int column = 0; column < debug_board_state[row].length; column++) {
System.out.print(debug_board_state[row][column] + " ");
}
System.out.println();
}
for (int row = 0; row < WIDTH_EASY; ++row) {
for (int column = 0; column < WIDTH_EASY; ++column) {
getCurrentState().board_elements[row][column] = new BoardElement();
getCurrentState().board_elements[row][column].max_connecting_bridges = Integer.parseInt(debug_board_state[row][column]);
getCurrentState().board_elements[row][column].row = row;
getCurrentState().board_elements[row][column].col = column;
if (getCurrentState().board_elements[row][column].max_connecting_bridges > 0) {
getCurrentState().board_elements[row][column].is_island = true;
}
}
}
}
private void setCurrentState(State new_state) {
this.current_state = new_state;
}
public State getCurrentState() {
return current_state;
}
}
What algorithm could I use to make sure the Map can be Solved (Islands Connected with Bridges) before spawning the nodes.
This is what the map looks like (don't mind the design)
One thing to consider would be to start with a blank board. Place an island. Then place another island that can be connected to the first one (i.e. on one of the four cardinal directions). Connect the two with a bridge, and increment each island's count.
Now, pick one of the two islands and place another island that it can connect. Add the bridge and increment.
Continue in this way until you've placed the number of islands that you want to place.
The beauty here is that you start with an empty board, and during construction the board is always valid.
You'll have to ensure that you're not crossing bridges when you place new islands, but that's pretty easy to do, since you know where the existing bridges are.

Pass Variables using Blocking Queue

At the moment I am trying to make my program pass the variables xPos and yPos from the ChessBoard class to the makeMove() method in HumanPlayer.
But at the moment it just gives null pointer exceptions in HumanPlayer.
Can this be done with BlockingQueues and if so what am I doing wrong?
HumanPlayer
import java.util.*;
import java.util.concurrent.BlockingQueue;
public class HumanPlayer extends Player implements Runnable{
private Scanner in;
protected BlockingQueue<Integer> queue = null;
int x;
int y;
public HumanPlayer(String n, Pieces p, Board b, Player o, BlockingQueue<Integer> queue) {
super(n, p, b, o);
this.queue = queue;
}
#Override
public void run() {
try{
x = queue.take();
y = queue.take();
}
catch (InterruptedException e){
e.printStackTrace();
}
}
public boolean makeMove() {
// declare board and selected piece
Board chess = getBoard();
Piece selected;
//take input of piece player wants to move
// in = new Scanner(System.in);
// System.out.println("Select Piece: ");
// System.out.print("x: ");
// String inputX = in.nextLine().toUpperCase();
// System.out.print("y: ");
// String inputY = in.nextLine();
// System.out.println(inputX+inputY);
// //if one of the inputs is >1 length then return false to stop error
// if (inputY.length()!=1 || inputX.length() !=1)
// return false;
// //change inputs to numbers to use in array
// int x = (int)(inputX.charAt(0)-'A');
// int y = (int)(inputY.charAt(0)-'0')-1;
run();
// if the input is in range of the board array select that piece if not return false
if ( x<=7 && x>=0 && y<=7 && y>=0){
selected = chess.getPiece(x,y);
System.out.println(x+""+y);
}
else
return false;
// check the piece selected is not null and is the players own piece
if ((selected != null)
&& (getPieces().getPiece(0).getColour() == selected.getColour() )) {
}
else
return false;
// get the position the player wants to move the piece to
// System.out.println("Select Move: ");
// System.out.print("x: ");
// String moveX = in.nextLine().toUpperCase();
// System.out.print("y: ");
// String moveY = in.nextLine();
// System.out.println(moveX+moveY);
// check the inputs length are > 1 to stop errors
// if (moveY.length()!=1 || moveX.length() !=1)
// return false;
// //change inputs to ints for array
// int mX = (int)(moveX.charAt(0)-'A');
// int mY = (int)(moveY.charAt(0)-'0')-1;
run();
int mX = x;
int mY = y;
//check the inputs are not > 7 or less than 0
if ( mX>7 || mX<0 || mY>7 || mY<0) {
return false;
}
//declare boolean and move
boolean occupied = getBoard().occupied(mX, mY);
Move requested = new Move(selected,x,y,mX,mY,occupied);
//check if the move is and available move
if ( selected.availableMoves().contains(requested) ){
//delete the opponents piece if its taken
if (occupied){
Piece remove = chess.getPiece(mX,mY);
chess.remove(mX, mY);
getOpponent().getPieces().delete(remove);
}
// move the piece to desired position
selected.setPosition(mX, mY);
chess.setPosition(mX, mY, selected);
chess.remove(x, y);
return true;
}
//return false if not and available move
return false;
}
}
ChessBoard
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.BlockingQueue;
import javax.swing.*;
#SuppressWarnings("serial")
public class ChessBoard extends JFrame implements ActionListener, Runnable{
JButton[][] squares;
private int xPos;
private int yPos;
protected BlockingQueue<Integer> queue = null;
public ChessBoard(BlockingQueue<Integer> queue){
this.queue = queue;
setSize(800,800);
setTitle("chess");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.setLayout(new GridLayout (8,8));
squares = new JButton[8][8];
Color lightBrown = new Color(222,184,135);
Color Brown = new Color(167,71,20);
for(int y=7; y>=0; y--){
for(int x=0; x<8; x++){
squares[x][y] = new JButton();
squares[x][y].addActionListener(this);
if ((x + y) % 2 == 0) {
squares[x][y].setBackground(Brown);
}
else {
squares[x][y].setBackground(lightBrown);
}
contentPane.add(squares[x][y]);
}
}
setVisible(true);
}
public JButton getButton(int x, int y){
return squares[x][y];
}
#Override
public void actionPerformed(ActionEvent e) {
JButton selected = (JButton) e.getSource();
for(int y=7; y>=0; y--){
for(int x=0; x<8; x++){
if( selected == squares[x][y]){
xPos = x;
yPos = y;
System.out.println(xPos+""+yPos);
}
}
}
}
public int getxPos() {
return xPos;
}
public int getyPos() {
return yPos;
}
#Override
public void run() {
try{
queue.put(xPos);
Thread.sleep(1000);
queue.put(yPos);
}
catch (InterruptedException e){
e.printStackTrace();
}
}
}

Analysing word frequencies in applet

i am writing a program in applet to measure the frequencies of word lengths in a given amount of text and display these frequencies during applet. i have written the program and it debugs without error.
however the output says i have 255 words of every length in the text i input, i have been staring at this for hours with no luck, i am aware that the drawstring method lists these outputs horizontally which i will be fixing at a later time.
i am assuming the problem resides in the analyseText method.
import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;
import java.awt.Graphics;
import java.util.*;
public class StringAnalysis extends Applet implements MouseListener, ActionListener {
Font arielBold;
Label pr_Label;
TextField pr_txt;
int textFieldSize = 15;
Button pr_input1, pr_input2, pr_input3;
String textToAnalyse = ("Nothing has been entered.");
boolean output = false;
String testing ="";
//create array to show respective lengths of words
int [] lengthsOfWords = new int[textFieldSize];
//first we must separate strings from spaces and populate array for comparison
String [] arrayOfWords = new String[textFieldSize];
public void init() {
pr_Label = new Label("Enter the text you wish to analise: ");
add(pr_Label);
pr_txt = new TextField(textFieldSize);
add(pr_txt);
pr_input1 = new Button("Analyse");
pr_input2 = new Button("Reset");
add(pr_input1);
add(pr_input2);
pr_input1.addActionListener(this);
pr_input2.addActionListener(this);
}
public void start (){
setSize(1000, 500);
arielBold = new Font ("Ariel", Font.BOLD, 20);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == pr_input2) {
showStatus("Resseting....");
reset();
}
else if (e.getSource() == pr_input1){
showStatus("Analysing...a");
textToAnalyse = pr_txt.getText();
analyseText(textToAnalyse);
}
}
public void paint(Graphics g) {
String statsToOutput = ("There are:" + "\n" );
int counter = 1;
for (int lengths: lengthsOfWords) {
statsToOutput = statsToOutput +lengthsOfWords[0] + " words of length " + counter + "\n ";
counter ++;
}
if (output = true){
g.drawString(statsToOutput, 25, 200);
g.drawString("The text to be analysed is: " + textToAnalyse, 25, 100);
showStatus("Finished.");
}
else if (output = false){
g.setFont(arielBold);
g.drawString(textToAnalyse,50, 100);
showStatus("Finished.");
}
}
public void analyseText(String text){
///////////////////////////////////////////////////////////////////////////////////////////////////////
int position1 = 0, position2 = 0;
String newWord = "";
String currentLetter;
int pos1 = 0, pos2 = 0;
for ( pos1 = 0; pos1 <= arrayOfWords.length-1; pos1++) {
//Initializes a string object for each address in array
for (position1 = 0; position1 <= text.length()-1; position1++){
//steps through each character in text
currentLetter = Character.toString(text.charAt(position1));
if (currentLetter.matches("[A-Z][a-z][0-9]")) {
//checks if character is alphanumeric using regular expressions (regex)
newWord = newWord + currentLetter;
//if passes regex then ads character to word
}
}
if (newWord.length() > 0) {
pos1 = arrayOfWords.length;
}
arrayOfWords[pos1] = newWord;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////
emptyArrayInt(lengthsOfWords);
//now compare each word with rest of array\
for ( pos2 = 0; pos2 <= arrayOfWords.length-1; pos2++) {
position2 = 0;
for (position2 = 0; position2 <= arrayOfWords.length-1; position2++){
if (arrayOfWords[pos2].length() == arrayOfWords[position2].length());
lengthsOfWords[arrayOfWords[pos2].length()] = lengthsOfWords[arrayOfWords[pos2].length()] + 1;
}
}
showStatus("finished analysing.");
output = true;
repaint();
}
public void emptyArrayInt(int[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = 0;
}
public void emptyArrayStr(String[] array) {
int position = 0;
for (position = 0; position <= array.length-1; position ++)
array[position] = "";
}
public void reset() {
pr_txt.setText("");
textToAnalyse = ("Nothing has been entered.");
emptyArrayInt(lengthsOfWords);
emptyArrayStr(arrayOfWords);
//repaint();
showStatus("Reset Successful.");
repaint();
}
public void mouseClicked(MouseEvent arg0) {}
public void mouseEntered(MouseEvent arg0) {}
public void mouseExited(MouseEvent arg0) {}
public void mousePressed(MouseEvent arg0) {}
public void mouseReleased(MouseEvent arg0) {}
i would appreciate any help on this please, (I'm desperate).
Let's try section of code :
private Map<String, int> freqWords = new HashMap<String, int>();
public void analyzeText(String text) {
// You can split with another type of delimiter
String regex = ....
String[] inputs = text.split(regex);
for (String s : inputs) {
if(freqWords.containtsKey(s)) {
int frequency = inputs.get(s);
frequency++;
inputs.put(s, frequency);
} else {
inputs.put(s, 1);
}
}
}
Hope that it can help you. The main point here is you should use data structure Map to store the frequency words.

accessing javascript from inside java

I know that there are lots of examples out there on this, but they all feel a little dated (even the sun docs) so I'm asking here to make sure what I'm doing is up to date. How would I go about talking to javascript from inside a java applet? Something simple like how to call alert() is all I'm looking for. Bonus points for a way to check if the browser has javascript enabled (this applet may be used in a school setting where having javascript turned off is a real possibility). All help is greatly appreciated, thanks in advance...
Code:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.JSObject;
public class TeamProject extends Applet implements ActionListener, MouseListener {
char[][] charValues = new char[10][10];
Table aTable;
boolean allowUserInput = false;
Button BtnStart;
Button randomChangeBtn;
boolean guessMode;
JSObject jso;
public void init() {
//setup buttons
BtnStart = new Button("add row/column");
BtnStart.addActionListener((ActionListener)this); //cast
randomChangeBtn = new Button("change one value");
randomChangeBtn.addActionListener((ActionListener)this);
//add button
this.add(BtnStart);
//add image to Image objects
Image imgO = getImage(getCodeBase(), "images/not.gif");
Image imgX= getImage(getCodeBase(), "images/cross.gif");
//setup table
aTable = new Table(100, 100, 75, 55, 5, 5, imgX, imgO);
//setBackground(Color.LIGHT_GRAY);
super.resize(700, 700);
//add mouse listener
addMouseListener(this);
//initially guessMode will be false
guessMode = false;
//to talk to javascript
jso = JSObject.getWindow(this);
}
public void paint(Graphics g) {
g.setColor(Color.black);
aTable.draw(g);
}
//Mouse listener methods
public void mousePressed (MouseEvent e) {
if(!guessMode){
if ((allowUserInput)) { //&&(aTable.isDrawable(e.getX(), e.getY())))
aTable.swapSquareValue(e.getX(), e.getY());
repaint();
}
} else {
System.out.println("guessed row = " + e.getY() + " guessed col = " + e.getX());
aTable.checkGuess(e.getX(), e.getY());
//repaint();
}
}
public void mouseClicked (MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseReleased (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
//Button action listener
public void actionPerformed(ActionEvent e) {
if (e.getSource() == BtnStart) {
aTable.addRow();
aTable.addColumn();
this.remove(BtnStart);
this.add(randomChangeBtn);
repaint();
} else if (e.getSource() == randomChangeBtn) {
//aTable.addRow();
aTable.randomChangeFunc();
repaint();
guessMode = true;
}
allowUserInput = true;
System.out.println(aTable.toString());
}
}
and my Table class:
import java.awt.*;
import java.util.Random;
public class Table {
private char[][]values = new char[10][10]; //probably better to use array of integer values(0 or 1)
Image imgO;
Image imgX;
private int Rows;
private int Columns;
private int BoxWidth ;
private int BoxHeight;
public Point Pos = new Point();
private int tableHeight;
private int tableWidth;
private int changedRow;
private int changedCol;
//constructor
public Table(int x, int y, int width, int height, int col, int rows, Image X, Image O) {
Rows = rows;
Columns = col;
BoxWidth = width;
BoxHeight = height;
Pos.x = x;
Pos.y = y;
imgX = X;
imgO = O;
tableHeight = Rows*BoxHeight;
tableWidth = Columns*BoxWidth;
this.setValues();
}
//draw table
public void draw(Graphics g) {
//draw vertical table lines
for (int i = 0 ; i <= Columns ; i++)
g.drawLine(i*BoxWidth + Pos.x, Pos.y, i*BoxWidth + Pos.x, tableHeight+Pos.y);
//draw horizontal table line
for(int i = 0 ; i <= Rows ; i++)
g.drawLine(Pos.x, i*BoxHeight + Pos.y, tableWidth+Pos.x, i*BoxHeight + Pos.y);
//draw values
drawValues(g);
}
public void swapSquareValue(int x, int y) {
if (this.isDrawable(x, y)) {
int col = this.getColumn(x)-1;
int row = this.getRow(y)-1;
if(values[row][col] == 'X')
values[row][col] = 'O';
else if(values[row][col] == 'O')
values[row][col] = 'X';
else
System.out.println("ERROR SWAPPING SQUARE VALUE");
} else
System.out.println("says not drawable");
}
public char getValue(int col, int row) {
return values[row][col];
}
//return true if (x,y) is a point in the table
public boolean isDrawable(int x, int y) {
if((this.getRow(y)!=-1)||(this.getColumn(x)!=-1))
return true;
else
return false;
}
public void addRow() {
Rows++;
tableHeight = (Rows*BoxHeight);
int numOfXs = 0;
for (int c=0; c < Columns; c++) {
numOfXs = 0;
for(int r = 0; r < Rows - 1; r++) {
if(values[r][c] == 'X'){
numOfXs++;
System.out.println("in column " + c + "new x found at " + r + " " + c + ", numOfXs = " + numOfXs);
}
if(numOfXs % 2 == 0) {
values[Rows - 1][c] = 'O';
} else{
values[Rows - 1][c] = 'X';
}
}//end inner for
System.out.println("end of column " + c);
}//end outer for
}// end function
public void addColumn() {
Columns++;
tableWidth = (Columns*BoxWidth);
int numOfXs = 0;
for (int r=0; r < Rows; r++) {
numOfXs = 0;
for(int c = 0; c < Columns - 1; c++) {
if(values[r][c] == 'X') {
numOfXs++;
System.out.println("in row " + r + "new x found at " + r + " " + c + ", numOfXs = " + numOfXs);
}
if(numOfXs % 2 == 0) {
values[r][Columns - 1] = 'O';
}
else {
values[r][Columns - 1] = 'X';
}
}//end inner for
System.out.println("end of row " + r);
}
}
//does not add or remove values
public void setColumn(int col) {
Columns = col;
tableWidth = (Columns*BoxWidth);
}
//does not add or remove values
public void setRows(int row) {
Rows = row;
tableHeight = (row*BoxHeight);
}
public String toString() {
String ValueString = "Displaying charValues[" + Rows + "][" + Columns + "]\n";
for (int r=0; r < Rows; r++) {
for (int c=0; c < Columns; c++) {
ValueString += (char)values[r][c];
}
ValueString += "\n"; //next line
}
return ValueString;
}
private void drawValues(Graphics g) {
Point drawPoint = new Point();
for (int r=0; r < Rows; r++)
for (int c=0; c < Columns; c++) {
drawPoint.x = Pos.x+BoxWidth*c;
drawPoint.y = Pos.y+BoxHeight*r;
//g.setColor(Color.white);
//g.fillRect(drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1);
if (values[r][c] == 'X') {
g.drawImage(imgX,drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1, null);
} else {
g.drawImage(imgO,drawPoint.x+1, drawPoint.y+1, BoxWidth-1, BoxHeight-1, null);
}
//System.out.print((char)values[r][c]);
}
g.setColor(Color.black);
}
//fills array with random values
private void setValues() {
for (int r=0; r < Rows; r++)
for (int c=0; c < Columns; c++) {
values[r][c] = this.randomChar();
}
}
//randomly return 'X' or 'O'
private char randomChar() {
char randomValue;
Random RandomGen = new Random();
if (RandomGen.nextInt(2)==0)
randomValue = 'O';
else
randomValue ='X';
return randomValue;
}
private int getColumn(int x) {
int offsetx=0;
for (int i = 0 ; i < Columns ; i++) {
offsetx = i*BoxWidth;
if((x>Pos.x+offsetx)&& (x<Pos.x+offsetx+BoxWidth))
return i+1;
}
return -1;
}
private int getRow(int y) {
int offsety=0;
for (int i = 0 ; i < Rows ; i++) {
offsety = i*BoxHeight;
if((y>Pos.y+offsety)&& (y<Pos.x+offsety+BoxHeight))
return i+1;
}
return -1;
}
public void randomChangeFunc() {
//get random row and column
Random rand=new Random();
int randRow = rand.nextInt(Rows);
int randCol = rand.nextInt(Columns);
System.out.println("randRow = " + randRow + " randCol = " + randCol);
/*THIS SHOULD BE HANDLED BY swapSquareValue(randCol,randRow)
/*BUT GETTING ERRORS (notDrawable). THE FOLLOWING CODE IS A WORK-AROUND
*/
if(values[randRow][randCol] == 'X')
values[randRow][randCol] = 'O';
else if(values[randRow][randCol] == 'O')
values[randRow][randCol] = 'X';
else
System.out.println("ERROR SWAPPING SQUARE VALUE");
//set globals
changedRow = randRow;
changedCol = randCol;
}
public void checkGuess(int guessCol, int guessRow){
int gCol = this.getColumn(guessCol)-1;
int gRow = this.getRow(guessRow)-1;
System.out.println("gCol = " + gCol + " gRow = " + gRow);
if(gCol == changedCol && gRow == changedRow) {
System.out.println("CORRECT!!!");
} else
System.out.println("incorrect :(");
}
}
Changing my javac command to:
javac -classpath /usr/lib/Java6u1/jre/lib/plugin.jar TeamProject.java
ignores my "Table" class and I get errors where I mention that. Any ideas?
Look at this article. If you try calling JS from applet on this page it definitely works, because there are js exception after update action from applet :)
import netscape.javascript.JSObject
public void init()
{
jso = JSObject.getWindow(this);
}
public void actionPerformed(ActionEvent e) {
if(jso != null )
try {
jso.call("updateWebPage", new String[] {txt.getText()});
}
catch (Exception ex) {
ex.printStackTrace();
}
}
EDIT:
For the classpath problem you need to add plugin.jar to your classpath which is located in %JAVA_HOME%\jre\lib\plugin.jar
EDIT2:
I think that your problem is that a class Table isn't compiled too:
try javac -classpath /usr/lib/Java6u1/jre/lib/plugin.jar TeamProject.java Table.java or use wildcards like *.java.
Maybe you should consider use IDE like Eclipse or Netbeans to compile and run project instead of struggling with command line tools.
As requested a sample which calls alert on the page it is embedded in (tested in Opera 10.01, FF 3.5.4, IE6).
Note the MAYSCRIPT in the applet tag, this MUST be present to enable java-javascript communication. As per default access to JSObject is disabled due to security reasons.
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<applet code="HelloWWW.class" width="300px" height="100px" MAYSCRIPT></applet>
</body>
</html>
Java (compile with javac -cp .;[pathtojre]/jre/lib/plugin.jar HelloWWW.java)
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import netscape.javascript.*;
public class HelloWWW extends Applet implements ActionListener {
Button runButton;
public void init() {
runButton = new Button("Run: alert(\"Hello WWW\")");
add(runButton);
runButton.addActionListener(this);
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == runButton) {
try {
//get JSOBject
JSObject jso = JSObject.getWindow(this);
//call alert with parameter passed as Object array
jso.call("alert", new Object[]{"Hello WWW"});
} catch (JSException e) {
e.printStackTrace();
}
runButton.setLabel("Did it!");
repaint();
}
}
}
Also check Java-to-Javascript Communication and Mozilla Dev: JSObject for further info.

Categories