Java multithreading application game never stops/ends - java

i am still learning java and i tried to program my first multithreading java application (horse race game) with NetBeans. It is a little bit frustrating at the moment, because the game starts, but never comes to an end/result. I hope somebody can help me. Thanks in advance. Here is my code:
package wettrennen;
import java.util.Random;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Pferd extends Thread{
public int entfernung;
public int nr;
public int y;
public int zug = 0;
public boolean aktiv;
//Constructor
public Pferd (int zug, int entfernung, boolean aktiv){
this.zug = zug;
this.entfernung = entfernung;
this.aktiv = true;
}
/**
* method, which makes each horse run
*/
public void rennen(){
int zufallszahl = (int)(Math.random()*4);
this.zug = +(zufallszahl*10);
this.entfernung+ = zug;
}
/**
* main method, which is automatically called for starting the threads
*/
public void run(){
while (aktiv = true && entfernung <= 270){
try {
rennen();
try {
sleep(1000);
} catch (Exception e) {
System.err.println("Sleeping is not working.");
}
} catch (Exception e) {
System.err.println("Racing is not working");
}
}
}
public int getZug(){
return zug;
}
public int getEntfernung(){
return entfernung;
}
public boolean getStatus(){
return aktiv;
}
public boolean setStatus(){
this.aktiv = false;
return aktiv;
}
}
Second class including the GUI and the Main method
package wettrennen;
import java.awt.*;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JFrame;
public class Wettrennen extends JFrame {
Thread thread;
Vector<Pferd> pferde;
Vector<Thread> threads;
public int numPlayer;
public int entfernung;
public int laenge;
public boolean aktiv;
public final int y = 50;
public Graphics g;
/**
* Creates new form Game
*/
public Wettrennen() {
initComponents();
}
/**
* GUI regenerated by the Form Editor.
*/
...
/**
* action event method which is called after pressing the start button
* #param evt
*/
private void StartActionPerformed(java.awt.event.ActionEvent evt) {
numPlayer = getNumPlayer();
initializeHorses();
initializeThreads();
startThreads();
while (aktiv = true) {
zeichnen();
}
}
/**
* action event method, which ist called after pressing the clear button
* #param evt
*/
private void ClearActionPerformed(java.awt.event.ActionEvent evt) {
destroy();
stop();
}
/**
* the (one and only) main method
* #param args the command line arguments
*/
public static void main(String args[]) {
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Wettrennen().setVisible(true);
}
});
}
/**
* method that gets the Number of Players from the input field
* #return
*/
public int getNumPlayer() {
String iputNumPlayer = InputNumPlayer.getText();
int numPlayer = Integer.parseInt(iputNumPlayer);
return numPlayer;
}
/**
* method that initializes the number of horses referring to the number players
*/
public void initializeHorses(){
pferde = new Vector<Pferd>();
for (int i = 0; i < numPlayer; i++) {
pferde.add(new Pferd(0, 0,true));
}
}
/**
* method which sorts every horse to a thread
*/
public void initializeThreads(){
threads = new Vector<Thread>();
for (int i = 0; i < pferde.size(); i++) {
threads.add(new Thread(pferde.get(i)));
}
}
/**
* method starting all initialized threads
*/
public void startThreads(){
for (int k = 0; k < threads.size(); k++) {
System.out.println("Methode startThreads()");
threads.get(k).start();
}
}
/**
* the paint method which organises that the course of each horse is displayed on canvas
* after the parameter entfernung of one horse reaches 270 the game ist over,
* the aktiv parameter of each horse is set false and
* the main thread (game) is set null
*/
public void zeichnen (){
Graphics g = canvas.getGraphics();
thread = new Thread();
if (threads != null) {
for (int j = 0; j < threads.size(); j++) {
int zug = pferde.get(j).getZug();
int entfernung = pferde.get(j).getEntfernung();
g.setColor(Color.red);
g.drawLine(50, y + j*50, 50 + zug, y + j*50);
if (entfernung >= 270) {
g.drawString("Horse" + threads.get(j) + "won.", 10, 10);
System.out.println("Horse" + threads.get(j) + "won.");
pferde.get(j).setStatus();
thread = null;
stop();
} else {
repaint();
}
}
} else {
g.drawString("Thread is null", 10, 10);
}
}
/**
* method quitting the game
*/
public void destroy(){
thread = null;
}
/**
* method for stopping and quitting the game
*/
public void stop(){
thread = null;
threads = null;
}
}

Related

Java How to send data over network VIA a UI button

I'm learning about sockets and how server/client communicates.
So far, I have my protocols figured out and managed to simulate a synthetic TCP three-way-handshake:
Client successfully connects to server and sends SYN.
Server receives SYN and replies SYNACK to client.
Client receives SYNACK, and replies ACK to server.
Thats it, all this is linearly executed in the Run() method under a while(true) loop of my Runnable client service in a new Thread. I don't know how a Button in the GUI class can tell my Client Service to send a specific packet when, say, a specific button in the UI is pressed while the service runs in a different thread.
I have an idea but correct me on this: somehow add ActionListeners for all the buttons in my GUI inside the Service class instead of the GUI..
Thanks.
PS. I'm using DataInputStream and DataOutputStream to read/write data from/to socket stream.
ClientService.java:
public class ClientService implements Runnable, GameProtocol {
private Socket socket;
private int clientNumber;
private GameClient client;
private JTextArea clientConsole;
private DataInputStream fromServer;
private DataOutputStream toServer;
public ClientService(Socket aSocket, GameClient aClient, JTextArea textArea) {
this.socket = aSocket;
this.client = aClient;
this.clientConsole = textArea;
}
private void buildStreams() throws Exception {
this.fromServer = new DataInputStream(this.socket.getInputStream());
this.toServer = new DataOutputStream(this.socket.getOutputStream());
}
public void sendPacket(int data) {
try {
this.toServer.writeInt(data);
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public void flushPacket() {
try {
this.toServer.flush();
} catch (Exception e) {
e.printStackTrace();
}
return;
}
public void run() {
try {
try {
buildStreams();
toServer.writeInt(PLAYER_SYN); // start synthetic three way handshake
toServer.flush();
if(fromServer.readInt() == SERVER_SYNACK) {
this.clientNumber = fromServer.readInt();
clientConsole.append("Client number from Server: " + clientNumber + "\n");
toServer.writeInt(PLAYER_ACK);
toServer.writeInt(this.clientNumber);
toServer.flush();
}
else {
clientConsole.append("Client -> Server Sync failed. Can't proceed.\n");
toServer.writeInt(PLAYER_QUIT);
toServer.flush();
socket.close();
System.exit(-1);
}
executeCommand();
} finally {
socket.close();
}
} catch (Exception e) {
System.out.println("Client Service: " + e.getMessage());
}
}
private void executeCommand() throws Exception {
boolean quit = false;
while(!quit) {
int command = -14324;
if(fromServer.available() > 0) {
command = fromServer.readInt();
}
switch (command) {
case WINNER:
clientConsole.append("You Win.\n");
break;
case LOSER:
clientConsole.append("You Lost.\n");
break;
case ENABLE_TURN:
client.enableTurn();
break;
case DISABLE_TURN:
client.disableTurn();
break;
}
}
}
}
GameClient.java:
public class GameClient extends JFrame implements GameProtocol {
/**
* TextArea size.
*/
private final int
TEXTAREA_ROWS = 5,
TEXTAREA_COLS = 40;
/**
* Client window size, unadjustable.
*/
private final int
FRAME_W = 535,
FRAME_H = 600;
// for Assignment 10
private Socket socket;
private DataOutputStream toServer;
private DataInputStream fromServer;
/**
* ArrayList of type Cards, by default, holds 20 cards.
*/
private ArrayList<Card> cards;
/**
* Console for debugging.
*/
private JTextArea gameConsole;
/**
* Button to terminate game
*/
private JButton quitButton;
/**
* Main Frame panels, cardsPanel and consolePanel are sub-panels of mainPanel.
*/
private JPanel mainPanel, cardsPanel, consolePanel;
/**
* Builds packets to be sent to the server
*/
private Packet packet;
/**
* players points, accumulated.
*/
private int points = 0;
/**
* card choice 1
*/
private int choice1 = -1;
/**
* card choice 2
*/
private int choice2 = -1;
/**
* for building packet arguments
*/
private static int packetBuilderCount = 0;
/**
* Counter for outbound and inbound packets
*/
private static int packetNumber = 1;
/**
* for timing out cards when recieving no match
*/
private Timer timer;
/**
* true when user is allowed to pick cards.
* false when another user is true
*/
private boolean isTurn = true;
// service
private ClientService service;
/**
* default contrustor. Builds JFrame and all components.
*/
public static void main(String[] args) {
new GameClient();
}
public GameClient() {
packet = new Packet();
buildButton();
buildCards();
addEventToCards(); // adds actionlistener to each card.
buildPanel();
buildTimer();
buildFrame();
buildConnection(); // for assignment 10
}
private void buildConnection() {
try {
this.socket = new Socket(HOST, PORT);
// this.toServer = new DataOutputStream(socket.getOutputStream());
// this.fromServer = new DataInputStream(socket.getInputStream());
gameConsole.append("Socket Connected\n");
service = new ClientService(socket, this, this.gameConsole);
new Thread(service).start();
} catch (SecurityException ex) {
System.out.println("Check your firewall or antivirus. Unable to establish connection to server.");
} catch (UnknownHostException ex) {
System.out.println("Host can't be found. Unable to establish connection to server.");
} catch (ConnectException ex) {
System.out.println("Connection refused. What now?");
ex.printStackTrace();
// ex.printStackTrace();
} catch (IOException ex) {
System.out.println("fuck......");
}
}
/**
* initializes the timer.
*/
private void buildTimer() {
int delay = 3000; // wait for 3000ms
timer = new Timer(delay, new AbstractAction() {
/**
* event handler for timer. Flips the cards back to face down position.
*/
#Override
public void actionPerformed(ActionEvent ae) {
flipCard(choice1, 10);
flipCard(choice2, 10);
}
});
}
/**
* Initializes JFrame
*/
private void buildFrame() {
this.setSize(FRAME_W, FRAME_H);
setResizable(false);
this.add(mainPanel);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
/**
* Initializes and compiles panels together. Adds Cards to panels
*/
private void buildPanel() {
gameConsole = new JTextArea(TEXTAREA_ROWS, TEXTAREA_COLS);
JScrollPane scrollConsole = new JScrollPane(gameConsole);
scrollConsole.setHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_NEVER);
gameConsole.setEditable(false);
mainPanel = new JPanel();
mainPanel.setPreferredSize(new Dimension(535, 475));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
cardsPanel = new JPanel(new GridLayout(4, 5, 20, 20));
for(int i = 0; i < 20; i++) {
cardsPanel.add(this.cards.get(i));
}
consolePanel = new JPanel();
consolePanel.add(scrollConsole);
consolePanel.add(quitButton);
mainPanel.add(cardsPanel);
mainPanel.add(consolePanel);
}
/**
* builds quit button, adds action listener to handle click
*/
private void buildButton() {
quitButton = new JButton("Quit");
quitButton.addActionListener(e -> {
buildQuitPacket();
});
}
/**
* builds 20 Card object.
*/
private void buildCards() {
cards = new ArrayList<Card>();
Card temp;
for(int i = 0; i < 20; i++) {
temp = new Card();
cards.add(temp);
}
}
/**
* adds actionlistener to all 20 card objects.
*/
private void addEventToCards() {
for(int i = 0; i < 20; i++) {
final int INDEX = i;
cards.get(i).addActionListener(e -> buildButtonPacket(this.cards.get(INDEX).getId()));
}
}
/**
* Builds and sends a Packet when a card is chosen
* #param value The card ID which was chosen.
*/
private void buildButtonPacket(int value) {
if(!isTurn) {
this.gameConsole.append("Its not you're turn.\n");
return;
}
if(packetBuilderCount == 0) {
packet.writeCommandToPacket(PICKED_CARDS);
packet.writeValueToPacket(value);
packetBuilderCount++;
choice1 = value;
}
else if(packetBuilderCount == 1) {
packet.writeValueToPacket(value);
packetBuilderCount = 0;
writeToConsoleOutBound(packet.toString());
choice2 = value;
// try{
// out.print(this.packet.getPacket());
// out.flush();
// } catch (Exception e) {
// gameConsole.append("could not send packet.\n");
// }
packet.clearPacket();
}
}
/**
* For handling commands from recieved Packet
* #param recieved the Packet object recieved. Gets and handles command and possible arguments that follows.
* See GameProtocol class for packet command definitions.
*/
public void handlePacket(Packet recieved) {
int cmd = recieved.getCommand();
writeToConsoleInBound(recieved.toString());
int arg1 = -99;
int arg2 = -99;
switch (cmd) {
case SERVER_SYNACK:
arg1 = recieved.getFirstArg();
if(arg1 == 1) {
this.isTurn = true;
}
else if (arg1 == 0) {
this.isTurn = false;
}
else {
writeToConsoleError("Server sync failed. Terminating..");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
writeToConsoleError(ex.getMessage());
} finally {
System.exit(-1);
}
}
break;
case CARDMATCH:
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 > 9) {
arg1 = 9;
}
if(arg2 > 9) {
arg2 = 9;
}
flipCard(choice1, arg1);
flipCard(choice2, arg2);
break;
case CARDNOMATCH:
// System.out.println("CLIENT: im going to sleep");
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 > 9) {
arg1 = 9;
}
if(arg2 > 9) {
arg2 = 9;
}
flipCard(choice1, arg1);
flipCard(choice2, arg2);
this.cardsPanel.revalidate();
this.cardsPanel.repaint();
this.consolePanel.revalidate();
this.consolePanel.repaint();
timer.setRepeats(false); //the timer should only go off once
timer.start();
break;
case SHOW_CARD:
arg1 = recieved.getFirstArg();
arg2 = recieved.getSecondArg();
if(arg1 < 0 || arg1 > 19) {
writeToConsoleError(" BAD PACKET ARGUMENT 1, \nCard index out of bounds");
}
else if(arg2 < 0 || arg2 > 10) {
writeToConsoleError(" BAD PACKET ARGUMENT 2, \nImage index out of bounds");
}
else {
flipCard(arg1, arg2);
}
break;
case ENABLE_TURN:
this.isTurn = true;
break;
case DISABLE_TURN:
this.isTurn = false;
break;
case WINNER:
this.gameConsole.append("You win!\n");
break;
case LOSER:
this.gameConsole.append("You lost :( \n");
break;
case ADD_POINTS:
arg1 = recieved.getFirstArg();
this.points += arg1;
this.gameConsole.append("** Gained " + Integer.toString(arg1) + ", you now have " + Integer.toString(this.points) + " points.\n");
break;
case OTHER_QUIT:
this.gameConsole.append("Other player forfeited. You win!\n");
break;
}
}
/**
* Builds a packet containing QUIT when quit button is pressed
* Only available when isTurn == true.
*/
private void buildQuitPacket() {
if(this.isTurn == false) {
this.gameConsole.append("You can only quit when it is your turn.");
return;
}
service.sendPacket(PLAYER_QUIT);
service.flushPacket();
// this.service.sendPacket(PLAYER_QUIT);
// this.service.flushPacket();
System.exit(0);
}
/**
* Writes the outgoing packet to the game console.
* #param msg the actual packet message.
*/
public void writeToConsoleOutBound(String msg) {
this.gameConsole.append(Integer.toString(packetNumber++) + ": SENDING: " + msg + "\n");
}
/**
* Writes the incoming packet to the game console.
* #param msg the actual packet message.
*/
public void writeToConsoleInBound(String msg) {
this.gameConsole.append(Integer.toString(packetNumber++) + ": RECEIVING: " + msg + "\n");
}
/**
* Writes an error to the game console.
* #param msg the error message.
*/
public void writeToConsoleError(String msg) {
this.gameConsole.append("Error handling packet number " + Integer.toString(packetNumber) + "." + msg + "\n");
}
/**
* Flips a Card object and show an image
* #param whichCard the card ID which will be flipped.
* #param imgID the image which will be shown on the flipped card.
*/
public void flipCard(int whichCard, int imgID) {
this.cards.get(whichCard).flipCard(imgID);
}
/**
* Accumulates points.
* #param amt the amount to be added.
*/
public void gainPoints(int amt) {
this.points += amt;
}
public void enableTurn() {
this.isTurn = true;
}
public void disableTurn() {
this.isTurn = false;
}
}
Your connection to a socket works because it is in a constructor, no calls to modify a rendered element have been made (say update a button's text). Your client service needs a loop waiting for requests made by the UI, otherwise you would need to create a thread with every request made by the UI. It will become a bottleneck, specially in a game when one user action can trigger several UI updates. Look at the code posted you should follow more or less that pattern
package so;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.ConcurrentLinkedQueue;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
class ClientService implements Runnable{
JLabel label;
ConcurrentLinkedQueue<Long> work;
#Override
public void run() {
Long i = null;
try{
while(true){
if ((i = work.poll()) != null){
final long ii = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
label.setText(ii + "");
}
});
}
Thread.sleep(10);
}
}
catch(Exception x){
}
}
}
class GameClient extends JFrame{
Thread worker;
ConcurrentLinkedQueue<Long> work;
private JLabel label;
private JButton button;
GameClient(){
setLayout(new GridLayout(2, 1));
label = new JLabel("Label");
button = new JButton("Button");
button.addMouseListener(new MouseListener(){
#Override
public void mouseClicked(MouseEvent e) {
work.add(System.currentTimeMillis());
}
#Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
});
this.add(label);
this.add(button);
work = new ConcurrentLinkedQueue<Long>();
ClientService cs = new ClientService();
cs.label = this.label;
cs.work = this.work;
this.worker = new Thread(cs);
this.worker.start();
}
}
class SOCLass {
public static void main(String[] args){
SOCLass m = new SOCLass();
GameClient frame = new GameClient();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
frame.worker.interrupt();
System.exit(0);
}
});
frame.pack();
frame.setVisible(true);
}
}

Making a jar manifest. Where does it come from do I make my own?

I recently created a simple tic tac toe program and I've been trying to make it into a jar and I using cmd. I manage to get the jar,but when I click it nothing happens. After more research I figure it's a manifest problem as I didn't do anything to it or can even find one. Now this manifest thing has been really confusing me I have created my own manifest several times as just a txt, but that didn't work and I read that it would create it's own manifest, but I couldn't find that anywhere. Can Someone clarify were this manifest comes from or how to create one.
Java code:
import javax.swing.JFrame;
import java.awt.Container;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.JButton;
import javax.swing.JLabel;
public class TicTacToe extends JFrame {
// GUI constants
private static final int WIDTH = 400; // display width
private static final int HEIGHT = 300; // display height
// TicTacToe layout constants
private static final int NUM_ROWS = 3; // number of tic-tac-toe rows
private static final int NUM_COLS = 3; // number of tic-tac-toe columns
private static final int TOTAL_CELLS = NUM_ROWS * NUM_COLS;
private static final int MAX_MOVES = NUM_ROWS * NUM_COLS; // max number of moves
// TicTacToe image, message and default cell value constants
private static final ImageIcon X_IMAGE = new ImageIcon("images.jpg", ""); // image for X
private static final ImageIcon O_IMAGE = new ImageIcon("O.jpg", ""); // image for O
private static final String GAME_ENDS_IN_TIE = "nobody wins cause blame john wells"; // tie message
private static final String NON_PLAYER_CELL_VALUE = "-"; // "-" is a non player cell
// Private TicTacToe members
private JButton[] cells;
private CellButtonHandler[] cellHandlers;
private String gameWinner;
private int xGoesFirst;
// private int[] press = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
// private String xMess = "Cross for you laymens out there";
// private String oMess = "Naught for you laymens out there";
private String pOne;
private String pTwo;
// private int pOneWins;
// private int pTwoWins;
private int count = 0;
/**
* Default Constructor
*/
public TicTacToe() {
// JFrame frame = new JFrame();
// SWING OPERATIONS
Container pane = getContentPane();
pane.setLayout(new GridLayout(NUM_ROWS, NUM_COLS));
cells = new JButton[TOTAL_CELLS];
cellHandlers = new CellButtonHandler[TOTAL_CELLS];
for (int i = 0; i < TOTAL_CELLS; i++) {
cells[i] = new JButton(NON_PLAYER_CELL_VALUE);
cellHandlers[i] = new CellButtonHandler();
cells[i].addActionListener(cellHandlers[i]);
pane.add(cells[i]);
}
setTitle("Tic Tac Toe");
setSize(WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// END SWING OPERATIONS
// CLASS OPERATIONS
this.setGameWinner(GAME_ENDS_IN_TIE);
this.xGoesFirst = 1;
this.pOne = "X";
this.pTwo = "O";
// this.pOneWins = 0;
// this.pTwoWins = 0;
// END CLASS OPERATIONS
} // public TicTacToe()
/**
* setGameWinner
*
* #param who - the game winner as a String.
*/
private void setGameWinner(String who) {
this.gameWinner = who;
} // private void setGameWinner(String who)
/**
* getGameWinner
*
* #return the game winner
*/
public String getGameWinner() {
return this.gameWinner;
} // public String getGameWinner()
/**
* Entry point of the program.
*
* #param args - <code>String[]</code> of runtime arguments
*/
public static void main(String[] args) {
// Swing is not thread safe, use SwingUtilities#invokeLater
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TicTacToe();
}
});
} // public static void main(String[] args)
/**
* CellButtonHandler
*/
private class CellButtonHandler implements ActionListener {
/**
* actionPerformed
*/
#Override
public void actionPerformed(ActionEvent e) {
JButton pressed = (JButton) e.getSource();
pressed.setText(TicTacToe.this.getCurrentPlayer());
// pressed.setIcon(TicTacToe.this.getCurrentPlayerIcon());
TicTacToe.this.count++;
if (TicTacToe.this.gameOverWin() || TicTacToe.this.gameOverTie()) {
System.out.println(TicTacToe.this.getGameWinner());
winScreen();
}
for (MouseListener ml : pressed.getMouseListeners()) {
pressed.removeMouseListener(ml);
}
} // public void actionPerformed(ActionEvent e)
} // private class CellButtonHandler implements ActionListener
/**
* private String getCurrentPlayer()
*/
private String getCurrentPlayer() {
this.xGoesFirst = this.xGoesFirst * -1;
if (this.xGoesFirst == -1) {
return pOne;
}
return pTwo;
} // private String getCurrentPlayer()
/**
* getCurrentPlayerIcon
*/
private ImageIcon getCurrentPlayerIcon() {
this.xGoesFirst = this.xGoesFirst * -1;
if (this.xGoesFirst == -1) {
return X_IMAGE;
}
return O_IMAGE;
} // private ImageIcon getCurrentPlayerIcon()
/**
* Checks if the game ended in a win.
*
* #return true if someone has won the game.
*/
private boolean gameOverWin() {
if (rowChecker() || colomnChecker() || diagChecker()) {
return true;
}
return false;
} // private boolean gameOverWin()
/**
* Checks if the game ended in a tie.
*
* #return true if there are no more moves to be made.
*/
private boolean gameOverTie() {
if (this.count >= MAX_MOVES) {
return true;
}
return false;
} // private boolean gameOverTie()
/**
* Checks the rows for a win.
*
* #return true if one of the rows contains three X's or three O's.
*/
public boolean rowChecker() {
int row = 0; // row variable
int col = 0; // column variable
String mark = ""; // string to hold the first
// button in a row's text value
while (row != NUM_ROWS) {
col = row * NUM_ROWS;
mark = this.getCellText(col);
if (mark.equals(NON_PLAYER_CELL_VALUE)) {
row = row + 1;
continue;
}
if (this.cellsAreEqual(mark, col + 1)
&& this.cellsAreEqual(mark, col + 2)) {
this.setGameWinner("Row Winner: " + mark);
return true;
}
row = row + 1;
}
// no win across the rows so we return false
return false;
} // public boolean rowChecker()
/**
* Checks the diagonals for a win.
*
* #return true if one of the diagonals contains three X's or three O's.
*/
public boolean diagChecker() {
int leftToRight = 0; // start at the top left box
int rightToLeft = 0; // start at the top right box
int step = 0; // the number of cells to step over
String mark = ""; // string to hold the buttons mark
// first we'll start by checking the top-left to
// bottom-right diagonal
leftToRight = 0;
step = NUM_COLS + 1;
mark = this.getCellText(leftToRight);
if (!mark.equals(NON_PLAYER_CELL_VALUE)) {
if (this.cellsAreEqual(mark, step)
&& this.cellsAreEqual(mark, (step * 2))) {
this.setGameWinner("Diagonal Winner: " + mark);
return true;
}
}
// next we'll check the top-right to bottom-left diagonal
rightToLeft = NUM_COLS - 1;
step = NUM_COLS - 1;
mark = this.getCellText(rightToLeft);
if (!mark.equals(NON_PLAYER_CELL_VALUE)) {
if (this.cellsAreEqual(mark, rightToLeft + step)
&& this.cellsAreEqual(mark, rightToLeft + (step * 2))) {
this.setGameWinner("Diagonal Winner: " + mark);
return true;
}
}
// no win on the diagonals so we return false
return false;
} // public boolean diagChecker()
/**
* colomnChecker
*/
public boolean colomnChecker() {
int row = 0; // row variable
int col = 0; // column variable
String mark = ""; // string to hold the buttons mark
while (col != NUM_COLS) {
row = col;
mark = getCellText(row);
if (mark.equals(NON_PLAYER_CELL_VALUE)) {
col = col + 1;
continue;
}
if (this.cellsAreEqual(mark, row + 3)
&& this.cellsAreEqual(mark, row + 6)) {
this.setGameWinner("Column Winner: " + mark);
return true;
}
col = col + 1;
}
// no win down the columns so we return false
return false;
} // public boolean colomnChecker()
/**
* getCellText
*/
private String getCellText(int which) {
return this.cells[which].getText();
} // private String getCellText(int which)
/**
* cellsAreEqual
*/
private boolean cellsAreEqual(String mark, int index) {
return mark.equals(this.getCellText(index));
} // private boolean cellsAreEqual(String mark, int index)
// private class restart implements ActionListener
public boolean winScreen(){
Container pane = getContentPane();
pane.removeAll();
pane.repaint();
JLabel label=new JLabel(TicTacToe.this.getGameWinner()+" won");
label.setHorizontalAlignment(JLabel.CENTER);
label.setVerticalAlignment(JLabel.BOTTOM);
JLabel back=new JLabel(new ImageIcon("moniz_475.JPEG"));
pane.add(back);
pane.add(label);
return true;
}
} // public class TicTacToe extends JFrame
manifest file:
Main-Class: Tic_Tac_Toe.TicTacToe
If you want to add a manifest file to a jar you have to use jar -cfm command.
For example you have a manifest file name Manifest.txt which you want to add to your jar tictactoe.jar the the command will be.
jar -cfm tictactoe.jar Manifest.txt *
If you want to mention main class you have to add an entry in the manifest file as follows.
Main-Class: <fully qualified name for the class>
Also check the default program for jar files is properly configured.
Update
Your Java class is not in a package so your manifest file should be.
Main-Class: TicTacToe
If you want the class in a package then add the package package tictactoe; in the first line above the import statements. The in manifest file should be.
Main-Class: tictactoe.TicTacToe
For more info check Setting an Application's Entry Point
Are you using an IDE? If so most IDEs have the option of directly exporting your Java program as a jar with Manifest created. What you need to have in your META-INF/MANIFEST.MF file is the main method and any dependent libraries in the class path.
Add the following in your MANIFEST.MF file :
Main-Class: com.example.MainClass
Class-Path: lib/library.jar
Give the full path to the class with main method in Main-Class and any dependent libraries in Class-Path.
Now you can try creating the jar.

How can I play Adobe Flash .SWF files in a Java Desktop Application? [duplicate]

I'm having a problem in adding my swf file to my jframe. They say that i should try the JFlashplayer but it is only a trial one. Can you give me some sample code for this?
Here is my flash player adapted from the example on their website. BCFrame is essentially a JInternalFrame. You can have it extend whatever. It will need slight modification to work, but should be strait forward. You can rip out anything that doesnt exist.
Other possible solutions are:
jffmpeg - do a search for it
http://www.humatic.de/htools/dsj/samplecode.php?WebM.java
http://code.google.com/p/gstreamer-java/
http://www.xuggle.com/xuggler/
http://www.theregister.co.uk/2010/08/20/flash_in_java/
package Components.FlashPlayer;
import Components.BCFrame;
import GUI.BCApp.DataTypeEnum;
import Logging.LogRunner;
import Properties.Basic.FlashPlayer_Prop;
import XMLProcessing.Helpers.XMLActionInfoHolder;
import XMLProcessing.XMLUtilities;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
// import the JFlashPlayer package
import com.jpackages.jflashplayer.*;
import java.net.URL;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* This class plays a flash video.
* Create with help from: http://www.jpackages.com/jflashplayer , see the website
* for a larger example of how to do more things with this code. I kind of modified
* this to fit the current needs of the project. This works in conjunction with
* dlls that need to go in the win32 folder. For linux/mac, look into the Apple
* Java Quicktime API
* #author dvargo
*/
public class FlashPlayer extends BCFrame implements FlashPanelListener {
/**
* handle to a FlashPanel instance
*/
FlashPanel flashPanel;
final Label currentFrameLabel = new Label("Frame: N/A");
final JProgressBar progressBar = new JProgressBar();
JButton playButton,stopButton,forwardButton,rewindButton,backButton;
JCheckBox loopCheckBox;
private boolean isMovieSet = false;
FrameMonitorThread fmt;
boolean loop = false;
boolean playOnStart = true;
public enum Actions
{
Loop,
Stop,
Play
}
/**
* Defualt constructor
*/
public FlashPlayer()
{
}
/**
* Sets FlashPlayer to defualt size
* #param x X position for the player
* #param y Y position for the player
* #param mainWindow Reference to the main window
*/
public FlashPlayer(int x, int y, GUI.Window mainWindow) {
this(x, y, 600, 400, mainWindow);
}
/**
* Full consturtor
* #param x X position for this player
* #param y Y position for this player
* #param w Width of the player
* #param h Height of the player
* #param mainWindow reference to the main window
*/
public FlashPlayer(int x, int y, int w, int h, GUI.Window mainWindow) {
super(x, y, w, h, mainWindow);
initComponents();
this.getContentPane().setLayout(new BorderLayout());
createButtons();
addCurrCompSetter(flashPanel,progressBar,currentFrameLabel,playButton,stopButton,forwardButton,rewindButton,loopCheckBox,backButton);
}
#SuppressWarnings("unchecked")
//
private void initComponents() {
videoPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
videoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
javax.swing.GroupLayout videoPanelLayout = new javax.swing.GroupLayout(videoPanel);
videoPanel.setLayout(videoPanelLayout);
videoPanelLayout.setHorizontalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 381, Short.MAX_VALUE)
);
videoPanelLayout.setVerticalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 247, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}//
// Variables declaration - do not modify
private javax.swing.JPanel videoPanel;
// End of variables declaration
/**
* FlashPanelListener event method which receives FSCommand Flash events.
*
* You should use ExternalInterface.call instead of FSCommand
* with the latest ActionScript version. Older ActionScript versions
* will only have access to FSCommand.
*/
public void FSCommand(String command, String arg) {
System.out.println("FlashPlayer (ignoring): FSCommand event received: " + command + " " + arg);
}
private void creatFlashPlayerWorker()
{
// add the FlashPanel to the frame
this.getContentPane().add(flashPanel, BorderLayout.CENTER);
// specify the object for Flash ExternalInterface.call events to search for the called method on
flashPanel.setFlashCallObject(this);
// specify the FlashPanelListener in case a movie is using the older FSCommand event
flashPanel.addFlashPanelListener(this);
// specify variables for a flash movie which are available from the start of the
// movie as long as this is called before the FlashPanel is visible
flashPanel.setVariables("myGreeting=hi&myNumber=1&myVar=good%20job");
isMovieSet = true;
centerAndDisplay();
fmt = new FrameMonitorThread(flashPanel);
fmt.start();
revalidate();
if(!playOnStart)
{
stop();
}
setLoop(loop);
}
/**
* Create a FlashPanel instance and add it to the frame
*/
public void createFlashPanel(String url) {
// install Flash 10 if Flash 6 or greater is not present
//FlashPanel.installFlash("6");
dataSource = dataSource.url;
setData("Path",url.toString());
String flashVersionRequired = "9";
try
{
FlashPanel.setRequiredFlashVersion(flashVersionRequired);
flashPanel = new FlashPanel(new URL(url));//new File(flashFilePath));
}
catch (JFlashLibraryLoadFailedException e)
{
exitError("A required library (DLL) is missing or damaged.");
}
catch(JFlashInvalidFlashException e)
{
exitError("Required version " + flashVersionRequired + " of Flash is not installed. ");
}
catch (Exception e)
{
exitError("Something went wrong!\n" + e.toString());
}
creatFlashPlayerWorker();
}
/**
* Create a FlashPanel instance and add it to the frame
*/
public void createFlashPanel(File file) {
// install Flash 10 if Flash 6 or greater is not present
//FlashPanel.installFlash("6");
//http://samples.mplayerhq.hu/SWF/flash_adpcm_testfiles/stereo_22.swf
dataSource = dataSource.file;
setData("Path",file.getAbsolutePath());
String flashVersionRequired = "9";
try
{
FlashPanel.setRequiredFlashVersion(flashVersionRequired);
flashPanel = new FlashPanel(file);//new File(flashFilePath));
}
catch (JFlashLibraryLoadFailedException e)
{
exitError("A required library (DLL) is missing or damaged.");
}
catch(JFlashInvalidFlashException e)
{
exitError("Required version " + flashVersionRequired + " of Flash is not installed. ");
}
catch (Exception e)
{
exitError("Something went wrong!\n" + e.toString());
}
creatFlashPlayerWorker();
}
public boolean isMovieSet()
{
return isMovieSet;
}
public boolean isPlayOnStart()
{
return playOnStart;
}
public boolean isLoop()
{
return loop;
}
public void setPlayOnStart(boolean dis)
{
playOnStart = dis;
}
public void setIsLoop(boolean dis)
{
loop = dis;
}
/**
* Select a different SWF file at remote url
*/
public void setMovie(URL url)
{
if(!isMovieSet)
{
createFlashPanel(url.toString());
return;
}
setData("Path",url.toString());
dataSource = dataSource.url;
flashPanel.setMovie(url);
}
/**
* Select a different SWF file at remote url
*/
public void setMovie(String url)
{
if(!isMovieSet)
{
createFlashPanel(url);
return;
}
setData("Path",url);
dataSource = dataSource.url;
try
{
flashPanel.setMovie(new URL(url));
revalidate();
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Could not play Flash Movie at " + url);
}
}
/**
* Select a different SWF file on local machine
*/
public void setMovie(File file)
{
setData("Path",file.getAbsolutePath()); //setting this to absolute path might cause a problem
dataSource = dataSource.file;
try
{
if(isMovieSet)
{
flashPanel.setMovie(file);
}
else
{
createFlashPanel(file);
}
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Could not play Flash Movie at " + file);
}
}
/**
* Instruct the flash movie to play.
*/
public void play()
{
flashPanel.play();
}
/**
* Instruct the flash movie to stop playing.
*/
public void stop()
{
flashPanel.stop();
}
/**
* Instruct the flash movie to go back one frame.
* This will also stop the movie if it was playing.
*/
public void rewind()
{
rewind(1);
}
/**
* Instruct the flash movie to go back x number of frames.
* This will also stop the movie if it was playing.
* #param numberOfFrames The number of frames to rewind
*/
public void rewind(int numberOfFrames)
{
for(int i = 0; i &lt numberOfFrames; i++)
{
flashPanel.back();
}
}
/**
* Instruct the flash movie to go forward 1 frame.
* This will also stop the movie if it was playing.
*/
public void forward()
{
forward(1);
}
/**
* Instruct the flash movie to go forward x number of frame.
* This will also stop the movie if it was playing.
*/
public void forward(int numberOfFrames)
{
for(int i = 0; i &lt numberOfFrames; i++)
{
flashPanel.forward();
}
}
/**
* Instruct the flash movie to rewind to the first frame.
* This will also stop the movie if it was playing.
*/
public void goBackToBegining()
{
flashPanel.rewind();
}
/**
* Select and set the flash movie background color.
*/
public void backgroundAction(Color c)
{
flashPanel.setBackground(c);
}
/**
* Instruct the flash movie to loop or not.
*/
void setLoop(boolean loop) {
flashPanel.setLoop(loop);
}
/**
* Define some buttons to demonstrate JFlashPlayer functionality
*/
void createButtons() {
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
playButton = new JButton("Play");
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
play();
}
});
buttonPanel.add(playButton);
JButton stopButton = new JButton("Pause");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stop();
}
});
buttonPanel.add(stopButton);
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
goBackToBegining();
}
});
buttonPanel.add(backButton);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
forward();
}
});
//buttonPanel.add(forwardButton);
rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rewind();
}
});
buttonPanel.add(rewindButton);
loopCheckBox = new JCheckBox("Loop");
loopCheckBox.setSelected(true);
loopCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setLoop(loopCheckBox.isSelected());
}
});
progressBar.setVisible(true);
buttonPanel.add(progressBar);
for (int i = 0; i screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
//this.setLocation((screenSize.width - frameSize.width) / 2,
// (screenSize.height - frameSize.height) / 2);
this.setVisible(true);
//this.toFront();
}
#Override
protected void createProperties()
{
properties = new FlashPlayer_Prop(this);
}
#Override
public void action(Enum a)
{
}
#Override
public Enum convertStringToActionEnumValue(String in) {
return null;
}
#Override
public void build(HashMap theDictionary, String filePath, String DataSource, ArrayList actions)
{
if(DataSource.equals(DataTypeEnum.url.toString()))
{
createFlashPanel((String) theDictionary.get("Path"));
setDataSource(DataTypeEnum.url);
}
else
{
String theFile = XMLUtilities.parseFilePath(filePath) + File.separator + (String) theDictionary.get("Path");
createFlashPanel(new File(theFile));
setDataSource(DataTypeEnum.file);
}
playOnStart = Boolean.parseBoolean(theDictionary.get("PlayOnStart"));
loop = Boolean.parseBoolean(theDictionary.get("Loop"));
//add actions to the component
setActions(XMLUtilities.getActions(this, actions));
}
#Override
public Element extractData(Document dom)
{
setData("PlayOnStart",Boolean.toString(playOnStart));
setData("Loop", Boolean.toString(loop));
return super.extractData(dom);
}
#Override
public File[] extractFiles(String filePath)
{
File retVal = new File(getData("Path"));
if(retVal == null)
{
return null;
}
setData("Path","files" + File.separator + retVal.getName());
return new File[]{retVal};
}
#Override
public void drag(File[] theFiles)
{
//if they dragged a one file in
if(theFiles.length == 1)
{
//try and set it as the image of this component
setMovie(new File(theFiles[0].getAbsolutePath()));
}
//they dragged multiple files in
else
{
for(int i = 0; i &lt theFiles.length; i++)
{
int location = (i * 5) % mainWindow.getComponentContentPane().getHeight();
FlashPlayer temp = new FlashPlayer(location,location , mainWindow);
temp.createFlashPanel(new File(theFiles[i].getAbsolutePath()));
mainWindow.getCurrPage().addComponent(temp);
mainWindow.getCurrPage().loadPage();
}
}
}
#Override
public BCFrame copy(int x, int y) {
try
{
FlashPlayer clone = new FlashPlayer(x,y,this.getWidth(),this.getHeight(),mainWindow);
clone.setTitleBarVisible(this.isTitleBarRemoved());
clone.setActions(this.getActions());
if(dataSource == dataSource.file)
{
clone.setMovie(new File(this.getData("Path")));
}
else
{
clone.setMovie(this.getData("Path"));
}
clone.setPlayOnStart(isPlayOnStart());
clone.setIsLoop(isLoop());
return clone;
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Cant clone this compoenent");
}
return null;
}
/**
* Thread to poll the current frame of the flash movie to be displayed
*/
class FrameMonitorThread extends Thread {
FlashPanel flashPanel;
FrameMonitorThread(FlashPanel fp) {
flashPanel = fp;
}
public void run() {
while (true) {
if (flashPanel != null) {
final long currentFrame = flashPanel.getCurrentFrame();
final long totalFrames = flashPanel.getTotalFrames();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
double cf = currentFrame;
double tf = totalFrames;
double result = cf/tf;
int percent = (int)(100 * result);
try{progressBar.setValue(percent);}catch(Exception e){}
currentFrameLabel.setText("Frame: " + currentFrame + "/" + totalFrames);
}
});
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
/**
* Checks whterer the dlls that flash player needs are in their correct spot
* #return True if all the dlls could be found, false otherwise
*/
public static boolean checkDlls()
{
String systemFolder = "C:\\WINDOWS\\system32\\";
String [] dlls = new String[]{"atl2k.dll","atl98.dll","jflash.dll"};
for(String x : dlls)
{
if(!new File(systemFolder + x).exists())
{
return false;
}
}
return true;
}
}
One option is to embed a web browser, and let that load Flash Player.
See: Embed a web browser within a java application

Class linked into start button won't run

In a GUI in Java, when I click a Start button, I want this main class WumpusWorld to run a certain method. I then want the GUI to refresh and see a change. At the moment, I click Start and nothing happens. EDIT - I am going to give you guys the full classes I am using. You should be able to run them in Eclipse. I just want this program to do SOMETHING when I click start, because at the moment it is doing NOTHING.
WumpusWorld.java (main class)
import java.util.LinkedList;
public class WumpusWorld {
private static int size;
private static Node startpoint;
private static Node endpoint;
private static int mode;
//private static String[][] nodeTypes;
private static LinkedList<Node> thegrid;
private static WumpusGui wgui;
public static void main(String[] args) {
// Show the GUI
thegrid = new LinkedList<Node>();
wgui = new WumpusGui();
// Set an initial size*/
setSize(5);
}
// Set up the grid
public static void setUpGrid() {
thegrid.clear();
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
thegrid.add(new Node(i, j, "empty"));
}
}
wgui.setGridSize(size);
wgui.setGrid(thegrid);
}
/**
*
*/
public static void run() {
mode = 0; // Manhattan Heuristic
// Ensure that the grid is valid
int start = 0;
int end = 0;
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
if(thegrid.get(i*size+j).isGoal()) {
end++;
endpoint = thegrid.get(i*size+j);
} else if(thegrid.get(i*size+j).isRobot()) {
start++;
startpoint = thegrid.get(i*size+j);
}
}
}
if(!(start == 1 && end == 1)) {
return;
}
Pathfinder pathf = new Pathfinder(thegrid);
String temp = pathf.pathfind(startpoint, endpoint, mode);
temp = temp.substring(1);
temp = temp.substring(0, temp.length()-1);
String[] result = temp.split("\\)\\(");
int finalcounter = result.length;
LinkedList<Node> victoryPath = new LinkedList<Node>();
for (String a : result) {
String[] b = a.split(",");
victoryPath.add(new Node(Integer.parseInt(b[0]), Integer.parseInt(b[1]), "empty"));
System.out.println("lol");
}
for(Node n : victoryPath) {
thegrid.get(n.getX()*size + n.getY()).setType("path");
}
}
// Setter for size
public static void setSize(int newSize) {
size = newSize;
setUpGrid();
}
public static void setStartPos(int x, int y) {
// Remove the old start pos
for(int i=0; i<size*size; i++) {
if(thegrid.get(i).isRobot()) {
thegrid.get(i).setType("empty");
break;
}
}
// Add the new pos
thegrid.get((x*size) + y).setType("robot");
}
public static void setEndPos(int x, int y) {
// Remove the old start pos
for(int i=0; i<size*size; i++) {
if(thegrid.get(i).isGoal()) {
thegrid.get(i).setType("empty");
break;
}
}
// Add the new pos
thegrid.get((x*size) + y).setType("goal");
}
public static void setObstacle(int x, int y) {
// Add the obstacle
thegrid.get((x*size) + y).setType("wall");
}
public static void removeObstacle(int x, int y) {
// Add the obstacle
thegrid.get((x*size) + y).setType("empty");
}
}
WumpusGui.java (JPanel)
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.LayoutManager;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;
import javax.swing.*;
public class WumpusGui extends JFrame {
private static final long serialVersionUID = 1L;
// This GUI
private static WumpusGui wgui;
// Controls
// NxN Grid Input
private JPanel pnlLayoutGrid;
private JLabel lblGrid;
private JTextField txtGrid;
private JButton btnGrid;
// Obstacle input
private JPanel pnlLayoutObstacles;
private JLabel lblObstacleX;
private JTextField txtObstacleX;
private JLabel lblObstacleY;
private JTextField txtObstacleY;
private JButton btnObstacleAdd;
private JLabel lblObstacleLog;
private JPanel pnlLayoutObstacleButtons;
// Start and end box positions
private JPanel pnlStartEndPos;
private JPanel pnlStartPos;
private JLabel lblStartX;
private JTextField txtStartX;
private JLabel lblStartY;
private JTextField txtStartY;
private JButton btnStartPos;
private JPanel pnlEndPos;
private JLabel lblEndPos;
private JLabel lblEndX;
private JTextField txtEndX;
private JLabel lblEndY;
private JTextField txtEndY;
private JButton btnEndPos;
// Start and stop buttons
private JPanel pnlStartStop;
private JButton btnStart;
private JButton btnStop;
// Display
private JPanel pnlDisplay;
private JPanelGrid pnlGraphics;
private JLabel pnlText;
// Window layouts
private JPanel pnlTop;
private JPanel pnlTopLeft;
private JPanel pnlTopRight;
public WumpusGui() {
// Set up window
setTitle("Wumpus World GUI");
setBackground(Color.GRAY);
// Set up controls
Dimension d = new Dimension(50, 25);
// Set up basic layout
pnlTop = new JPanel();
add(pnlTop, BorderLayout.NORTH);
pnlTopLeft = new JPanel();
pnlTopLeft.setLayout(new BoxLayout(pnlTopLeft, BoxLayout.Y_AXIS));
pnlTopRight = new JPanel();
pnlTop.add(pnlTopLeft, BorderLayout.WEST);
pnlTop.add(pnlTopRight, BorderLayout.EAST);
// Set up NxN grid controls
pnlLayoutGrid = new JPanel();
pnlLayoutGrid.setBorder(BorderFactory.createTitledBorder("Grid"));
pnlTopLeft.add(pnlLayoutGrid);
lblGrid = new JLabel("Grid size");
txtGrid = new JTextField();
txtGrid.setPreferredSize(d);
btnGrid = new JButton("Set size");
pnlLayoutGrid.add(lblGrid);
pnlLayoutGrid.add(txtGrid);
pnlLayoutGrid.add(btnGrid);
// Set up start and end position controls
pnlStartEndPos = new JPanel();
pnlStartEndPos.setLayout(new BoxLayout(pnlStartEndPos, BoxLayout.Y_AXIS));
pnlTopLeft.add(pnlStartEndPos);
pnlStartPos = new JPanel();
pnlStartPos.setBorder(BorderFactory.createTitledBorder("Start position"));
pnlStartEndPos.add(pnlStartPos);
lblStartX = new JLabel("X: ");
txtStartX = new JTextField();
txtStartX.setPreferredSize(d);
lblStartY = new JLabel("Y: ");
txtStartY = new JTextField();
txtStartY.setPreferredSize(d);
btnStartPos = new JButton("Set");
pnlStartPos.add(lblStartX);
pnlStartPos.add(txtStartX);
pnlStartPos.add(lblStartY);
pnlStartPos.add(txtStartY);
pnlStartPos.add(btnStartPos);
pnlEndPos = new JPanel();
pnlEndPos.setBorder(BorderFactory.createTitledBorder("End position"));
pnlStartEndPos.add(pnlEndPos);
lblEndX = new JLabel("X: ");
txtEndX = new JTextField();
txtEndX.setPreferredSize(d);
lblEndY = new JLabel("Y: ");
txtEndY = new JTextField();
txtEndY.setPreferredSize(d);
btnEndPos = new JButton("Set");
pnlEndPos.add(lblEndX);
pnlEndPos.add(txtEndX);
pnlEndPos.add(lblEndY);
pnlEndPos.add(txtEndY);
pnlEndPos.add(btnEndPos);
// Set up obstacles controls
pnlLayoutObstacles = new JPanel();
pnlLayoutObstacles.setBorder(BorderFactory.createTitledBorder("Obstacles"));
pnlLayoutObstacles.setLayout(new BoxLayout(pnlLayoutObstacles, BoxLayout.Y_AXIS));
pnlTopRight.add(pnlLayoutObstacles);
lblObstacleX = new JLabel("X: ");
txtObstacleX = new JTextField();
txtObstacleX.setPreferredSize(d);
lblObstacleY = new JLabel("Y: ");
txtObstacleY = new JTextField();
txtObstacleY.setPreferredSize(d);
btnObstacleAdd = new JButton("Add");
pnlLayoutObstacleButtons = new JPanel();
pnlLayoutObstacles.add(pnlLayoutObstacleButtons, BorderLayout.NORTH);
pnlLayoutObstacleButtons.add(lblObstacleX);
pnlLayoutObstacleButtons.add(txtObstacleX);
pnlLayoutObstacleButtons.add(lblObstacleY);
pnlLayoutObstacleButtons.add(txtObstacleY);
pnlLayoutObstacleButtons.add(btnObstacleAdd);
// Graphical display
pnlGraphics = new JPanelGrid();
pnlGraphics.setPreferredSize(new Dimension(200, 200));
pnlGraphics.setN(10);
pnlGraphics.setBackground(Color.WHITE);
add(pnlGraphics, BorderLayout.CENTER);
// Add the start button
btnStart = new JButton("Start");
pnlTopRight.add(btnStart, BorderLayout.SOUTH);
// Button setup
btnGrid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
WumpusWorld.setSize(Integer.parseInt(txtGrid.getText()));
pnlGraphics.repaint();
} catch(Exception ex) {
// Nothing
}
}
});
btnStartPos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
WumpusWorld.setStartPos(Integer.parseInt(txtStartX.getText()), Integer.parseInt(txtStartY.getText()));
pnlGraphics.repaint();
} catch(Exception ex) {
// Nothing
}
}
});
btnEndPos.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
WumpusWorld.setEndPos(Integer.parseInt(txtEndX.getText()), Integer.parseInt(txtEndY.getText()));
pnlGraphics.repaint();
} catch(Exception ex) {
// Nothing
}
}
});
btnObstacleAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
WumpusWorld.setObstacle(Integer.parseInt(txtObstacleX.getText()), Integer.parseInt(txtObstacleY.getText()));
pnlGraphics.repaint();
} catch(Exception ex) {
// Nothing
}
}
});
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
WumpusWorld.run();
pnlGraphics.repaint();
} catch(Exception ex) {
// Nothing
}
}
});
pnlGraphics.addMouseListener(new MouseListener() {
public void mouseClicked(MouseEvent e) {
// Get X and Y
int x = e.getX();
int y = e.getY();
// Left click = add obstacle
if(e.getButton() == MouseEvent.BUTTON1) {
pnlGraphics.addObstacle(x, y);
// Right click = remove obstacle
} else {
pnlGraphics.removeObstacle(x, y);
}
pnlGraphics.repaint();
}
// These methods are not used
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
});
// finish off the window
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void drawGrid(int n) {
// Draw the base grid
Graphics g;
}
public static WumpusGui get() {
return wgui;
}
public void setGridSize(int size) {
pnlGraphics.setN(size);
txtGrid.setText(String.valueOf(size));
}
// Set the grid in the graphics display
public void setGrid(LinkedList<Node> thegrid) {
pnlGraphics.setObstacles(thegrid);
}
// Private class used for displaying the grid visually
private class JPanelGrid extends JPanel {
private int n; // width/height of grid
private LinkedList<Node> obstacles;
private LinkedList<Clickable> clickables = new LinkedList<>();
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Set up dimensions
int width = getWidth();
int height = getHeight();
int gridX = 10;
int gridY = 10;
int gridW = width-20;
int gridH = height-20;
// Draw the grid's background
g.setColor(Color.BLACK);
g.fillRect(gridX, gridY, gridW, gridH);
// Empty the clickable list
clickables.clear();
// Draw cells
int nodePointer = 0;
if(obstacles != null) {
for(int i=0, ii=0; ii<n; i+=(gridW/n), ii++) {
for(int j=0, jj=0; jj<n; j+=(gridH/n), jj++) {
// Set the color depending on the node's type
if(obstacles.get(nodePointer).isEmpty()) {
g.setColor(Color.WHITE);
} else if(obstacles.get(nodePointer).isWall()) {
g.setColor(Color.DARK_GRAY);
} else if(obstacles.get(nodePointer).isRobot()) {
g.setColor(Color.RED);
} else if(obstacles.get(nodePointer).isEmpty()) {
g.setColor(Color.CYAN);
} else {
g.setColor(Color.YELLOW);
}
// Draw the rectangle
int x = gridX + (int)i + 1;
int y = gridY + (int)j + 1;
int w = gridW/n - 2;
int h = gridH/n - 2;
clickables.add(new Clickable(x, y, w, h, ii, jj));
g.fillRect(x, y, w, h);
// Draw the X and Y coords
g.setColor(Color.GRAY);
g.drawString("x" + ii + ", y" + jj, x+4, y+11);
nodePointer++;
}
}
}
}
// Setter for N (size)
public void setN(int n) {
this.n = n;
}
// Setter for obstacles
public void setObstacles(LinkedList<Node> obstacles) {
this.obstacles = obstacles;
}
public void addObstacle(int x, int y) {
for(Clickable c : clickables) {
if(c.inside(x, y)) {
WumpusWorld.setObstacle(c.getX(), c.getY());
}
}
}
public void removeObstacle(int x, int y) {
for(Clickable c : clickables) {
if(c.inside(x, y)) {
WumpusWorld.removeObstacle(c.getX(), c.getY());
}
}
}
// This class is used to allow the user to click on the grid to add an obstacle.
private class Clickable {
private Rectangle rect;
private int x;
private int y;
public Clickable(int rectX, int rectY, int width, int height, int x, int y) {
rect = new Rectangle(rectX, rectY, width, height);
this.x = x;
this.y = y;
}
public boolean inside(int x, int y) {
return rect.contains(x, y);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
}
}
Pathfinder.java (A* search algorithm)
import java.util.HashSet;
import java.util.HashMap;
import java.util.Iterator;
import java.lang.Math;
public class Pathfinder {
/**
* Variable for the cost of each movement on the grid. Only for up/down/left/right movement.
* Use {#link #setMovementCost(double)} to change from an external class.
*/
private double movementCost = 1.0;
/**
* Storage variable for the input
*/
private Iterable<Node> iterableInput; //Input
/**
* Storage variable for the G-cost of the node, in A*
* <p>
* F = G + H
*/
private HashMap<Node,Double> gmap; //map of travel cost
/**
* Storage variable for the F-cost of the node, in A*
* <p>
* F = G + H
*/
private HashMap<Node,Double> fmap; //map of predicted total cost
/**
* Storage variable for a map of the paths on the grid. Every evaluated node points to its predecessor.
*/
private HashMap<Node,Node> navmap; //map of path to each node
/**
* Variable for which Pathfinding Heuristic to use.
* <p>
* Used in {#link #heuristicCost(Node, Node, int)}
* <p>
* default = Manhattan Distance
* <p>
* 1 = Diagonal Distance
*/
private static int heuristicMode;
/**
* General Pathfinder constructor
* <p>
* Takes iterable input as a parameter - use anything that extends Iterable
*
* #param input iterable input of nodes/boxes, such as a list
*/
public Pathfinder(Iterable<Node> input) {
iterableInput=input;
}
/**
* Pathfind the correct path
* <p>
* There is only one public method and it returns a path in the form of a String.
* <p>
* Parsing the answer string is not included in this class.
*
* #param start the starting node
* #param goal the finishing node
* #param mode integer for the heuristic being used
* #return String path of the form (0,0)(0,1)...
*/
public String pathfind(Node start, Node goal, int mode) {
heuristicMode=mode;
return astar(start, goal);
}
/**
* A* method.
* <p>
* Algorithm adapted from Wikipedia.
*
* #param start the starting node
* #param goal the finishing node
* #return String path of the form (0,0)(0,1)...
*/
private String astar(Node start, Node goal) {
HashSet<Node> closedset = new HashSet<Node>(); //set of evaluated nodes
HashSet<Node> openset = new HashSet<Node>(); //set of nodes to be evaluated
openset.add(start); //first node to be evaluated
gmap=populateHashMap(iterableInput); //initialize HashMap of visited Nodes
navmap=new HashMap<Node,Node>();
fmap=populateHashMap(iterableInput);
//Heuristic: F=G+H
//F = total cost
//G = path cost
//H = heuristic cost
//put appropriate G for start
gmap.put(start, 0.0);
fmap.put(start, gmap.get(start) + ManhattanDistance(start, goal)); //heuristic cost of 0
Node current;
while(!openset.isEmpty()) {
current = getCheapest(openset);
if(sameNode(current, goal))
return constructPath(navmap,goal);
openset.remove(current);
closedset.add(current);
HashSet<Node> neighbors = getNeighbors(current, heuristicMode);
for(Node neighbor : neighbors) {
if(closedset.contains(neighbor))
continue;
double temp_g = gmap.get(current) + movementCost;
if(!openset.contains(neighbor) || temp_g<gmap.get(neighbor)) {
navmap.put(neighbor, current);
gmap.put(neighbor,temp_g);
fmap.put(neighbor, gmap.get(neighbor) + heuristicCost(neighbor, goal, heuristicMode));
if(!openset.contains(neighbor))
openset.add(neighbor);
}
}
}
return "failed";
}
/**
* Set the cost for each movement.
* <p>
* This is for the up/down/left/right directions. The cost for moving diagonally is calculated based on that.
* #param cost the cost of moving up/down/left/right
*/
public void setMovementCost(double cost) {
movementCost=cost;
}
//Cost Heuristic
/**
* Heuristic switch function.
*
* #param current the current node
* #param goal the goal node
* #param mode the switch integer. Default for Manhattan. 1 for Diagonal.
* #return the cost that the switched-to heuristic has calculated
*/
private double heuristicCost(Node current, Node goal, int mode) {
switch(mode){
case 1: return DiagonalDistance(current, goal);
default: return ManhattanDistance(current,goal);
}
}
//Manhattan Distance
/**
* Manhattan Distance heuristic.
* <p>
* Adapted from http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
*
* #param current the current node
* #param goal the goal node
* #return the H-cost of the current node
*/
private double ManhattanDistance(Node current, Node goal) {
return movementCost*(Math.abs(current.getX()-goal.getX())+Math.abs(current.getY()-goal.getY()));
}
//Diagonal Distance
/**
* Diagonal Distance heuristic.
* <p>
* Adapted from http://theory.stanford.edu/~amitp/GameProgramming/Heuristics.html
*
* #param current the current node
* #param goal the goal node
* #return the H-cost of the current node
*/
private double DiagonalDistance(Node current, Node goal) {
return movementCost*(Math.abs(current.getX()-goal.getX())+Math.abs(current.getY()-goal.getY())) + (Math.sqrt(2)*movementCost-2*movementCost)*Math.min(Math.abs(current.getX()-goal.getX()), Math.abs(current.getY()-goal.getY()));
}
//Populating the Navigation Map
//All Values set to -1.0
/**
* Populates HashMap with parameter iterable input
* #param input the input which gets fed into the hashmap
*/
private HashMap<Node,Double> populateHashMap(Iterable<Node> input) {
HashMap<Node,Double> hashmap = new HashMap<Node,Double>();
Iterator<Node> iterator=input.iterator();
while(iterator.hasNext()) {
hashmap.put(iterator.next(), -1.0);
}
return hashmap;
}
//Getting the Cheapest Node from a HashSet
/**
* Gets the cheapest node of the openset
* #param openset the set of open nodes
* #return the node with the cheapest F-cost
*/
private Node getCheapest(HashSet<Node> openset) {
Iterator<Node> iterator=openset.iterator();
Node thisNode = iterator.next();
Node nextNode;
while(iterator.hasNext()) {
nextNode=iterator.next();
if(fmap.get(nextNode)<fmap.get(thisNode))
thisNode=nextNode;
}
return thisNode;
}
//Get the Neighbors of a Node
/**
* Gets the neighbors of the parameter node, based on the Heuristic mode
*
* #param current the current node
* #param mode the Heuristic mode. See {#link #heuristicMode}
* #return a HashSet of the neighboring nodes
*/
private HashSet<Node> getNeighbors(Node current, int mode) {
HashSet<Node> result = new HashSet<Node>();
HashSet<Node> keySet=(HashSet<Node>) gmap.keySet();
Iterator<Node> iterator=keySet.iterator();
while(iterator.hasNext()) {
Node thisNode=iterator.next();
//Manhattan movement
if(thisNode.getX()+1 == current.getX() && thisNode.getY() == current.getY())
result.add(thisNode);
else if(thisNode.getX()-1 == current.getX() && thisNode.getY() == current.getY())
result.add(thisNode);
else if(thisNode.getX() == current.getX() && thisNode.getY()+1 == current.getY())
result.add(thisNode);
else if(thisNode.getX() == current.getX() && thisNode.getY()-1 == current.getY())
result.add(thisNode);
//Diagonal movement
else if(mode==1) {
if(thisNode.getX()+1 == current.getX() && thisNode.getY()+1 == current.getY())
result.add(thisNode);
else if(thisNode.getX()+1 == current.getX() && thisNode.getY()-1 == current.getY())
result.add(thisNode);
else if(thisNode.getX()-1 == current.getX() && thisNode.getY()+1 == current.getY())
result.add(thisNode);
else if(thisNode.getX()-1 == current.getX() && thisNode.getY()-1 == current.getY())
result.add(thisNode);
}
}
return result;
}
//Same Nodes
//Checks whether the nodes are the same, based on their x and y
/**
* Checks for node similarity. This is included here in order to reduce class inter-dependency
* <p>
* Compares the results from getX() and getY() for each node.
* #param thisNode the first compared node
* #param otherNode the second compared node
* #return TRUE if their coordinates are the same
*/
private boolean sameNode(Node thisNode, Node otherNode) {
return thisNode.getX()==otherNode.getX() && thisNode.getY()==otherNode.getY();
}
//Path Constructor
//Returns String of Nodes in the form of (0,0)(0,1)...
/**
* Constructs a path from the parameter node and the now valued {#link #navmap}
* <p>
* Returns String with tokens built in {#link #toNodeString(Node)}
*
* #param hashmap the navmap
* #param last the goal -or- last node
* #return the String of nodes leading to the parameter node
*/
private String constructPath(HashMap<Node,Node> hashmap, Node last) {
String t;
if(hashmap.containsKey(last)) {
t = constructPath(hashmap, hashmap.get(last));
return (t + last);
}
else {
return toNodeString(last);
}
}
//Nodes to Strings in the form of "(x,y)"
/**
* Turns a node into a String
*
* #param a the parameter node
* #return the node represented in the String form of "(x,y)"
*/
private String toNodeString(Node a) {
return "("+a.getX()+","+a.getY()+")";
}
}
Node.java (Node class)
public class Node {
private int x;
private int y;
private boolean isEmpty, isWall, isRobot, isGoal;
/**
* Basic constructor.
* <p>
* Takes coordinates x, y, and box type.
*
* #param x the X coordinate
* #param y the Y coordinate
* #param type String for the type: "empty", "wall", "robot", "goal"
*/
public Node(int x, int y, String type) {
this.x = x;
this.y = y;
isEmpty=false;
isWall=false;
isRobot=false;
isGoal=false;
if(type.equalsIgnoreCase("empty"))
isEmpty=true;
else if(type.equalsIgnoreCase("wall"))
isWall=true;
else if(type.equalsIgnoreCase("robot"))
isRobot=true;
else if(type.equalsIgnoreCase("goal"))
isGoal=true;
}
/**
* Gets the x coordinate.
*
* #return the X coordinate
*/
public int getX() {
return x;
}
/**
* Gets the y coordinate.
*
* #return the Y coordinate
*/
public int getY() {
return y;
}
/**
* Checks if empty.
*
* #return true if empty
*/
public boolean isEmpty() {
return isEmpty;
}
/**
* Checks if is wall.
*
* #return true if wall
*/
public boolean isWall() {
return isWall;
}
/**
* Checks if is robot.
*
* #return true if robot
*/
public boolean isRobot() {
return isRobot;
}
/**
* Checks if is goal.
* #return true if goal
*/
public boolean isGoal() {
return isGoal;
}
/**
* Sets the type of the box
* <p>
* Does nothing with invalid input
*
* #param type String representing the type: "empty", "wall", "robot", "goal"
*/
public void setType(String type) {
if(type.equalsIgnoreCase("empty")) {
isWall=false;
isEmpty=true;
isRobot=false;
isGoal=false;
}
else if(type.equalsIgnoreCase("wall")) {
isWall=true;
isEmpty=false;
isRobot=false;
isGoal=false;
}
else if(type.equalsIgnoreCase("robot")) {
isWall=false;
isEmpty=false;
isRobot=true;
isGoal=false;
}
else if(type.equalsIgnoreCase("goal")) {
isWall=false;
isEmpty=false;
isRobot=false;
isGoal=true;
}
}
}
Java uses a dedicated thread to manage GUI and related events, which is called Event Dispatch Thread. You can't execute an intensive task directly inside a ActionListener callback because this would execute on the Swing thread and make the GUI unresponsive.
You should use a different thread to manage this, there are many possible solution, like using a normal Thread that calls repaint() or a SwingWorker. Take a look here and here for further informations.

Embed .swf file to my Jframe

I'm having a problem in adding my swf file to my jframe. They say that i should try the JFlashplayer but it is only a trial one. Can you give me some sample code for this?
Here is my flash player adapted from the example on their website. BCFrame is essentially a JInternalFrame. You can have it extend whatever. It will need slight modification to work, but should be strait forward. You can rip out anything that doesnt exist.
Other possible solutions are:
jffmpeg - do a search for it
http://www.humatic.de/htools/dsj/samplecode.php?WebM.java
http://code.google.com/p/gstreamer-java/
http://www.xuggle.com/xuggler/
http://www.theregister.co.uk/2010/08/20/flash_in_java/
package Components.FlashPlayer;
import Components.BCFrame;
import GUI.BCApp.DataTypeEnum;
import Logging.LogRunner;
import Properties.Basic.FlashPlayer_Prop;
import XMLProcessing.Helpers.XMLActionInfoHolder;
import XMLProcessing.XMLUtilities;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
// import the JFlashPlayer package
import com.jpackages.jflashplayer.*;
import java.net.URL;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* This class plays a flash video.
* Create with help from: http://www.jpackages.com/jflashplayer , see the website
* for a larger example of how to do more things with this code. I kind of modified
* this to fit the current needs of the project. This works in conjunction with
* dlls that need to go in the win32 folder. For linux/mac, look into the Apple
* Java Quicktime API
* #author dvargo
*/
public class FlashPlayer extends BCFrame implements FlashPanelListener {
/**
* handle to a FlashPanel instance
*/
FlashPanel flashPanel;
final Label currentFrameLabel = new Label("Frame: N/A");
final JProgressBar progressBar = new JProgressBar();
JButton playButton,stopButton,forwardButton,rewindButton,backButton;
JCheckBox loopCheckBox;
private boolean isMovieSet = false;
FrameMonitorThread fmt;
boolean loop = false;
boolean playOnStart = true;
public enum Actions
{
Loop,
Stop,
Play
}
/**
* Defualt constructor
*/
public FlashPlayer()
{
}
/**
* Sets FlashPlayer to defualt size
* #param x X position for the player
* #param y Y position for the player
* #param mainWindow Reference to the main window
*/
public FlashPlayer(int x, int y, GUI.Window mainWindow) {
this(x, y, 600, 400, mainWindow);
}
/**
* Full consturtor
* #param x X position for this player
* #param y Y position for this player
* #param w Width of the player
* #param h Height of the player
* #param mainWindow reference to the main window
*/
public FlashPlayer(int x, int y, int w, int h, GUI.Window mainWindow) {
super(x, y, w, h, mainWindow);
initComponents();
this.getContentPane().setLayout(new BorderLayout());
createButtons();
addCurrCompSetter(flashPanel,progressBar,currentFrameLabel,playButton,stopButton,forwardButton,rewindButton,loopCheckBox,backButton);
}
#SuppressWarnings("unchecked")
//
private void initComponents() {
videoPanel = new javax.swing.JPanel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
videoPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(""));
javax.swing.GroupLayout videoPanelLayout = new javax.swing.GroupLayout(videoPanel);
videoPanel.setLayout(videoPanelLayout);
videoPanelLayout.setHorizontalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 381, Short.MAX_VALUE)
);
videoPanelLayout.setVerticalGroup(
videoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 247, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(videoPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}//
// Variables declaration - do not modify
private javax.swing.JPanel videoPanel;
// End of variables declaration
/**
* FlashPanelListener event method which receives FSCommand Flash events.
*
* You should use ExternalInterface.call instead of FSCommand
* with the latest ActionScript version. Older ActionScript versions
* will only have access to FSCommand.
*/
public void FSCommand(String command, String arg) {
System.out.println("FlashPlayer (ignoring): FSCommand event received: " + command + " " + arg);
}
private void creatFlashPlayerWorker()
{
// add the FlashPanel to the frame
this.getContentPane().add(flashPanel, BorderLayout.CENTER);
// specify the object for Flash ExternalInterface.call events to search for the called method on
flashPanel.setFlashCallObject(this);
// specify the FlashPanelListener in case a movie is using the older FSCommand event
flashPanel.addFlashPanelListener(this);
// specify variables for a flash movie which are available from the start of the
// movie as long as this is called before the FlashPanel is visible
flashPanel.setVariables("myGreeting=hi&myNumber=1&myVar=good%20job");
isMovieSet = true;
centerAndDisplay();
fmt = new FrameMonitorThread(flashPanel);
fmt.start();
revalidate();
if(!playOnStart)
{
stop();
}
setLoop(loop);
}
/**
* Create a FlashPanel instance and add it to the frame
*/
public void createFlashPanel(String url) {
// install Flash 10 if Flash 6 or greater is not present
//FlashPanel.installFlash("6");
dataSource = dataSource.url;
setData("Path",url.toString());
String flashVersionRequired = "9";
try
{
FlashPanel.setRequiredFlashVersion(flashVersionRequired);
flashPanel = new FlashPanel(new URL(url));//new File(flashFilePath));
}
catch (JFlashLibraryLoadFailedException e)
{
exitError("A required library (DLL) is missing or damaged.");
}
catch(JFlashInvalidFlashException e)
{
exitError("Required version " + flashVersionRequired + " of Flash is not installed. ");
}
catch (Exception e)
{
exitError("Something went wrong!\n" + e.toString());
}
creatFlashPlayerWorker();
}
/**
* Create a FlashPanel instance and add it to the frame
*/
public void createFlashPanel(File file) {
// install Flash 10 if Flash 6 or greater is not present
//FlashPanel.installFlash("6");
//http://samples.mplayerhq.hu/SWF/flash_adpcm_testfiles/stereo_22.swf
dataSource = dataSource.file;
setData("Path",file.getAbsolutePath());
String flashVersionRequired = "9";
try
{
FlashPanel.setRequiredFlashVersion(flashVersionRequired);
flashPanel = new FlashPanel(file);//new File(flashFilePath));
}
catch (JFlashLibraryLoadFailedException e)
{
exitError("A required library (DLL) is missing or damaged.");
}
catch(JFlashInvalidFlashException e)
{
exitError("Required version " + flashVersionRequired + " of Flash is not installed. ");
}
catch (Exception e)
{
exitError("Something went wrong!\n" + e.toString());
}
creatFlashPlayerWorker();
}
public boolean isMovieSet()
{
return isMovieSet;
}
public boolean isPlayOnStart()
{
return playOnStart;
}
public boolean isLoop()
{
return loop;
}
public void setPlayOnStart(boolean dis)
{
playOnStart = dis;
}
public void setIsLoop(boolean dis)
{
loop = dis;
}
/**
* Select a different SWF file at remote url
*/
public void setMovie(URL url)
{
if(!isMovieSet)
{
createFlashPanel(url.toString());
return;
}
setData("Path",url.toString());
dataSource = dataSource.url;
flashPanel.setMovie(url);
}
/**
* Select a different SWF file at remote url
*/
public void setMovie(String url)
{
if(!isMovieSet)
{
createFlashPanel(url);
return;
}
setData("Path",url);
dataSource = dataSource.url;
try
{
flashPanel.setMovie(new URL(url));
revalidate();
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Could not play Flash Movie at " + url);
}
}
/**
* Select a different SWF file on local machine
*/
public void setMovie(File file)
{
setData("Path",file.getAbsolutePath()); //setting this to absolute path might cause a problem
dataSource = dataSource.file;
try
{
if(isMovieSet)
{
flashPanel.setMovie(file);
}
else
{
createFlashPanel(file);
}
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Could not play Flash Movie at " + file);
}
}
/**
* Instruct the flash movie to play.
*/
public void play()
{
flashPanel.play();
}
/**
* Instruct the flash movie to stop playing.
*/
public void stop()
{
flashPanel.stop();
}
/**
* Instruct the flash movie to go back one frame.
* This will also stop the movie if it was playing.
*/
public void rewind()
{
rewind(1);
}
/**
* Instruct the flash movie to go back x number of frames.
* This will also stop the movie if it was playing.
* #param numberOfFrames The number of frames to rewind
*/
public void rewind(int numberOfFrames)
{
for(int i = 0; i &lt numberOfFrames; i++)
{
flashPanel.back();
}
}
/**
* Instruct the flash movie to go forward 1 frame.
* This will also stop the movie if it was playing.
*/
public void forward()
{
forward(1);
}
/**
* Instruct the flash movie to go forward x number of frame.
* This will also stop the movie if it was playing.
*/
public void forward(int numberOfFrames)
{
for(int i = 0; i &lt numberOfFrames; i++)
{
flashPanel.forward();
}
}
/**
* Instruct the flash movie to rewind to the first frame.
* This will also stop the movie if it was playing.
*/
public void goBackToBegining()
{
flashPanel.rewind();
}
/**
* Select and set the flash movie background color.
*/
public void backgroundAction(Color c)
{
flashPanel.setBackground(c);
}
/**
* Instruct the flash movie to loop or not.
*/
void setLoop(boolean loop) {
flashPanel.setLoop(loop);
}
/**
* Define some buttons to demonstrate JFlashPlayer functionality
*/
void createButtons() {
JPanel buttonPanel = new JPanel();
buttonPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
playButton = new JButton("Play");
playButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
play();
}
});
buttonPanel.add(playButton);
JButton stopButton = new JButton("Pause");
stopButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
stop();
}
});
buttonPanel.add(stopButton);
backButton = new JButton("Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
goBackToBegining();
}
});
buttonPanel.add(backButton);
forwardButton = new JButton("Forward");
forwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
forward();
}
});
//buttonPanel.add(forwardButton);
rewindButton = new JButton("Rewind");
rewindButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
rewind();
}
});
buttonPanel.add(rewindButton);
loopCheckBox = new JCheckBox("Loop");
loopCheckBox.setSelected(true);
loopCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
setLoop(loopCheckBox.isSelected());
}
});
progressBar.setVisible(true);
buttonPanel.add(progressBar);
for (int i = 0; i screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
//this.setLocation((screenSize.width - frameSize.width) / 2,
// (screenSize.height - frameSize.height) / 2);
this.setVisible(true);
//this.toFront();
}
#Override
protected void createProperties()
{
properties = new FlashPlayer_Prop(this);
}
#Override
public void action(Enum a)
{
}
#Override
public Enum convertStringToActionEnumValue(String in) {
return null;
}
#Override
public void build(HashMap theDictionary, String filePath, String DataSource, ArrayList actions)
{
if(DataSource.equals(DataTypeEnum.url.toString()))
{
createFlashPanel((String) theDictionary.get("Path"));
setDataSource(DataTypeEnum.url);
}
else
{
String theFile = XMLUtilities.parseFilePath(filePath) + File.separator + (String) theDictionary.get("Path");
createFlashPanel(new File(theFile));
setDataSource(DataTypeEnum.file);
}
playOnStart = Boolean.parseBoolean(theDictionary.get("PlayOnStart"));
loop = Boolean.parseBoolean(theDictionary.get("Loop"));
//add actions to the component
setActions(XMLUtilities.getActions(this, actions));
}
#Override
public Element extractData(Document dom)
{
setData("PlayOnStart",Boolean.toString(playOnStart));
setData("Loop", Boolean.toString(loop));
return super.extractData(dom);
}
#Override
public File[] extractFiles(String filePath)
{
File retVal = new File(getData("Path"));
if(retVal == null)
{
return null;
}
setData("Path","files" + File.separator + retVal.getName());
return new File[]{retVal};
}
#Override
public void drag(File[] theFiles)
{
//if they dragged a one file in
if(theFiles.length == 1)
{
//try and set it as the image of this component
setMovie(new File(theFiles[0].getAbsolutePath()));
}
//they dragged multiple files in
else
{
for(int i = 0; i &lt theFiles.length; i++)
{
int location = (i * 5) % mainWindow.getComponentContentPane().getHeight();
FlashPlayer temp = new FlashPlayer(location,location , mainWindow);
temp.createFlashPanel(new File(theFiles[i].getAbsolutePath()));
mainWindow.getCurrPage().addComponent(temp);
mainWindow.getCurrPage().loadPage();
}
}
}
#Override
public BCFrame copy(int x, int y) {
try
{
FlashPlayer clone = new FlashPlayer(x,y,this.getWidth(),this.getHeight(),mainWindow);
clone.setTitleBarVisible(this.isTitleBarRemoved());
clone.setActions(this.getActions());
if(dataSource == dataSource.file)
{
clone.setMovie(new File(this.getData("Path")));
}
else
{
clone.setMovie(this.getData("Path"));
}
clone.setPlayOnStart(isPlayOnStart());
clone.setIsLoop(isLoop());
return clone;
}
catch(Exception e)
{
LogRunner.dialogMessage(this.getClass(),"Cant clone this compoenent");
}
return null;
}
/**
* Thread to poll the current frame of the flash movie to be displayed
*/
class FrameMonitorThread extends Thread {
FlashPanel flashPanel;
FrameMonitorThread(FlashPanel fp) {
flashPanel = fp;
}
public void run() {
while (true) {
if (flashPanel != null) {
final long currentFrame = flashPanel.getCurrentFrame();
final long totalFrames = flashPanel.getTotalFrames();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
double cf = currentFrame;
double tf = totalFrames;
double result = cf/tf;
int percent = (int)(100 * result);
try{progressBar.setValue(percent);}catch(Exception e){}
currentFrameLabel.setText("Frame: " + currentFrame + "/" + totalFrames);
}
});
}
try {
Thread.sleep(100);
} catch (Exception e) {
}
}
}
}
/**
* Checks whterer the dlls that flash player needs are in their correct spot
* #return True if all the dlls could be found, false otherwise
*/
public static boolean checkDlls()
{
String systemFolder = "C:\\WINDOWS\\system32\\";
String [] dlls = new String[]{"atl2k.dll","atl98.dll","jflash.dll"};
for(String x : dlls)
{
if(!new File(systemFolder + x).exists())
{
return false;
}
}
return true;
}
}
One option is to embed a web browser, and let that load Flash Player.
See: Embed a web browser within a java application

Categories