Using AWT, I would like to save resources like flash does, by stopping draws to the screen when the window is hidden. But first, I need a method to detect if the Frame is completely covered by one or more other windows. Windows that are likely not from the same application, so I can't just sum up their shapes.
So the question is, is it possible to detect if the window is covered by other windows from other applications?
Everything is possible just you need some creativity and hard work :)
I hope you know that Java can call native Windows API (this won't be very performance vise, but we have only this way), for this we could use JNA lib which will give us access to native shared libraries.
I have done some quick concept check this code only checks if active window fully covers java application window, but you can iterate over visible windows and calculate area too, JNA gives that access too.
For my demo project I was using these JNA dependencies:
compile("net.java.dev.jna", "jna", "4.5.0")
compile("net.java.dev.jna", "jna-platform", "4.5.0")
My main class:
package com.sauliuxx.inc;
import com.sauliuxx.inc.workers.ActiveWindowChecker;
import com.sun.jna.platform.win32.WinDef;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* The type App.
*/
public class App extends Frame implements ActionListener {
private final String title = "Demo123";
private Label sizeLabel;
private Label positionLabel;
private Label visibleLabel;
BlockingQueue<WinDef.RECT> q =
new LinkedBlockingQueue<>();
private App() {
this.setTitle(title);
this.setLayout(new BorderLayout());
this.setSize(500, 500);
Panel infoPanel = new Panel();
sizeLabel = new Label(this.getSize().height + " X " + this.getSize().width);
infoPanel.add(sizeLabel);
positionLabel = new Label("X: " + this.getLocation().getX() + " Y: " + this.getLocation().getY());
infoPanel.add(positionLabel);
visibleLabel = new Label(this.isVisible() ? "true" : "false");
infoPanel.add(visibleLabel);
this.add(infoPanel, BorderLayout.PAGE_END);
Timer timer = new Timer(250, this);
timer.start();
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.addComponentListener(new ComponentListener() {
#Override
public void componentResized(ComponentEvent componentEvent) {
sizeLabel.setText(componentEvent.getComponent().getSize().height + " X " + componentEvent.getComponent().getSize().width);
}
#Override
public void componentMoved(ComponentEvent componentEvent) {
positionLabel.setText("X: " + componentEvent.getComponent().getLocation().getX() + " Y: " + componentEvent.getComponent().getLocation().getY());
}
#Override
public void componentShown(ComponentEvent componentEvent) {
visibleLabel.setText("true");
}
#Override
public void componentHidden(ComponentEvent componentEvent) {
visibleLabel.setText("false");
}
});
ActiveWindowChecker awcDeamon = new ActiveWindowChecker(q);
awcDeamon.setDaemon(true);
awcDeamon.start();
}
#Override
public void actionPerformed(ActionEvent actionEvent) {
WinDef.RECT rect = null;
try {
rect = q.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (this.isActive()) {
System.out.println("action");
} else {
//System.out.println("rect = " + (rect != null ? rect : ""));
//System.out.println("frame = [(" + (int)this.getLocation().getX() + "," + (int)this.getLocation().getY() + ") (" + this.getSize().width + "," + this.getSize().height + ")]");
// x and y windows to compare top left point
int rxTop = rect == null ? 0: rect.left;
int ryTop = rect == null ? 0:rect.top;
int fxTop = (int) this.getLocation().getX();
int fyTop = (int) this.getLocation().getY();
// bottom right points
int rxBottom = rect == null ? 0: rect.right;
int ryBottom = rect == null ? 0: rect.bottom;
int fxBottom = fxTop + this.getSize().width;
int fyBottom = fyTop + this.getSize().height;
if ((rxTop >= fxTop || ryTop >= fyTop) || (rxBottom <= fxBottom || ryBottom <= fyBottom))
{
System.out.println("Not covered by active window.");
}
else{
System.out.println("Covered by active window.");
}
}
}
/**
* The entry point of application.
*
* #param args the input arguments
*/
public static void main(String... args) {
if (!System.getProperty("os.name").contains("Windows")) {
System.err.println("ERROR: Only implemented on Windows");
System.exit(1);
}
java.awt.EventQueue.invokeLater(() -> new App().setVisible(true));
}
}
My worker class:
package com.sauliuxx.inc.workers;
import com.sun.jna.Native;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import java.util.concurrent.BlockingQueue;
/**
* The type Active window checker.
*/
public class ActiveWindowChecker extends Thread {
private static final int MAX_TITLE_LENGTH = 1024;
private final BlockingQueue<WinDef.RECT> queue;
/**
* Instantiates a new Active window checker.
*
* #param q the q
*/
public ActiveWindowChecker(BlockingQueue<WinDef.RECT> q) {
this.queue = q;
}
#Override
public void run() {
Exception ex = null;
while (ex == null) {
char[] buffer = new char[MAX_TITLE_LENGTH * 2];
WinDef.HWND hwnd = User32.INSTANCE.GetForegroundWindow();
User32.INSTANCE.GetWindowText(hwnd, buffer, MAX_TITLE_LENGTH);
System.out.println("Active window title: " + Native.toString(buffer));
WinDef.RECT rect = new WinDef.RECT();
User32.INSTANCE.GetWindowRect(hwnd, rect);
try {
queue.put(rect);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
ex = e;
}
}
}
}
Related
I've some issues with my code for studies, it's our first time with Java and I don't know how to change the icon of JRadioButtons contents in an array.
package exo_02_01;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JRadioButton;
import javax.swing.JToolBar;
#SuppressWarnings("serial")
public class ControleEtiquette extends JToolBar {
private ImageIcon[] m_iconesBoutons = new ImageIcon[18];
private JRadioButton[] m_boutons = new JRadioButton[6];
private String m_nomsIcones[] = { "bhgauche", "bhcentre", "bhdroite", "bvhaut", "bvcentre", "bvbas" };
private static final int NUMBER_BUTTONS = 6;
public ControleEtiquette() {
super();
chargerIcones();
creerBoutons();
}
private void chargerIcones() {
for (int i = 0; i < NUMBER_BUTTONS; i++) {
m_iconesBoutons[i] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + ".gif");
m_iconesBoutons[i + NUMBER_BUTTONS] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "R.gif");
m_iconesBoutons[i + NUMBER_BUTTONS * 2] = new ImageIcon("RESGRAF/" + m_nomsIcones[i] + "B.gif");
}
}
private void creerBoutons() {
for (int i = 0; i < m_boutons.length; ++i) {
m_boutons[i] = new JRadioButton(m_iconesBoutons[i]);
add(m_boutons[i]);
m_boutons[i].addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e)
{
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[0]);
}
public void mouseClicked(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[NUMBER_BUTTONS * 2 - 1]);
}
public void mouseExited(MouseEvent e) {
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[5]);
}
});
if (i == 2)
addSeparator();
}
}
My code in my chargerBoutons() method work well, but my aim is to set the icon according to the current button. I tried to do like
((JRadioButton) e.getSource()).setIcon(m_iconesBoutons[i]);
But i is undefined in this scope.
How can I fix it ?
Thanks
Actually, I think you set the icon correctly, but you have to ask for an update of the UI...
So add the call updateUI() at the end of your creerBoutonsmethod. (it apply on the toolbar (ie: your object).
see JToolbar
This game is connect four and at the end of the game I give the player an option
to play again. So if they want to play again I try clearing the canvas and resetting the board. I know basically nothing about doing java graphics so I'm
pretty certain the error stems from me not understanding something about the
graphics as opposed to the games logic.
If you look at the update gameState method right after I get input from the user
is when I try to reset everything. And when I say reset I mean remove all images and such from window. Instead of everything being removed it just locks up.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Color;
public class MainFrame extends JFrame
{
public static final String GAME_NAME = "Connect Four!";
private static final int _PLAYER_ONE_TURN = 1;
private static String _title;
private Board _gameBoard;
private ToolBar _buttons;
private boolean _humanVsHuman;
private int _gameIteration;
public MainFrame()
{
super();
final String INITIAL_GAME_MESSAGE = "Human Vs. Human? Default Computer "
+ "Vs. Human.";
final String MENU_TITLE = "Game Setup...";
final String[] MENU_OPTIONS = { "Yes!", "No!" };
_gameBoard = new Board(Game.BOARD_WIDTH, Game.BOARD_HEIGHT);
_buttons = new ToolBar(Game.BOARD_WIDTH);
_humanVsHuman = 0 == JOptionPane.showOptionDialog(this,
INITIAL_GAME_MESSAGE, MENU_TITLE, JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE, null, MENU_OPTIONS, MENU_OPTIONS[1]);
updateTitle();
setLayout(new BorderLayout());
setSize(Game.SCREEN_WIDTH, Game.SCREEN_HEIGHT);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(_buttons, BorderLayout.SOUTH);
setVisible(true);
}
public void paint(Graphics g)
{
GamePiece[][] board = _gameBoard.getBoard();
_buttons.repaint();
for (int x = 0; x < Game.BOARD_WIDTH; x++)
{
for (int y = 0; y < Game.BOARD_HEIGHT; y++)
{
if (board[x][y] != null)
{
g.setColor(
board[x][y].toString().equals(GamePiece.GAME_PIECE_BLUE)
? Color.BLUE : Color.RED);
g.fillOval((int) (x * (GamePiece.SIZE[0] * .92) + ((Game.SCREEN_WIDTH - (GamePiece.SIZE[0] * Game.BOARD_WIDTH)) / Game.BOARD_WIDTH) * x + 30), (int) (y * (GamePiece.SIZE[1] * .9) + ((Game.SCREEN_HEIGHT - (GamePiece.SIZE[1] * Game.BOARD_HEIGHT)) / Game.BOARD_HEIGHT) * y + 30),
GamePiece.SIZE[0], GamePiece.SIZE[1]);
}
}
}
}
public void updateTitle()
{
final String HUMAN = "HUMAN";
final String COMPUTER = "COMPUTER";
final String PLAYER = "PLAYER";
final String TURN = "TURN";
_title = GAME_NAME + " " + Game.VERSION + ": " + PLAYER + " "
+ (getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? _humanVsHuman ? "1" : HUMAN
: _humanVsHuman ? "2" : COMPUTER)
+ " " + TURN;
setTitle(_title);
}
public void updateGameState(boolean aWinner)
{
final String AGAIN = "Play Again?";
final String ROUND_OVER = "ROUND OVER";
final String[] OPTIONS = { "Yes", "No" };
boolean hasWinner = aWinner;
if (hasWinner || _gameBoard.isFull())
{
if (hasWinner)
{
JOptionPane.showMessageDialog(this,
getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? "Blue won!" : "Red won!");
}
if (0 != JOptionPane.showOptionDialog(this, AGAIN, ROUND_OVER,
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
OPTIONS, OPTIONS[1]))
{
setVisible(false);
dispose();
}
else
{
_gameBoard.clearBoard();
removeAll();//or remove(JComponent)
invalidate();
_buttons = new ToolBar(Game.BOARD_WIDTH);
updateMainFrame();
}
}
_gameIteration++;
}
public void updateMainFrame()
{
revalidate();
repaint();
updateTitle();
if (_gameIteration + 1 == Integer.MAX_VALUE)
{
if (getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN)
{
_gameIteration = 0;
}
else
{
_gameIteration = 1;
}
}
}
private int getPlayerTurn(int iteration)
{
return (iteration % 2) + 1;
}
private class ToolBar extends JPanel
{
public ToolBar(int numberOfButtons)
{
setLayout(new FlowLayout(FlowLayout.CENTER,
(int) (Game.SCREEN_WIDTH / numberOfButtons) / 2, 0));
for (int i = 0; i < numberOfButtons; i++)
{
JButton button = new JButton("" + (i + 1));
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
boolean hasWinner;
if (!_gameBoard
.isRowFull(Integer.parseInt(button.getText()) - 1))
{
hasWinner = _gameBoard.insert(
getPlayerTurn(_gameIteration) == _PLAYER_ONE_TURN
? new BluePiece() : new RedPiece(),
Integer.parseInt(button.getText()) - 1);
updateMainFrame();
updateGameState(hasWinner);
}
}
});
add(button);
}
}
}
}
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 < 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 < 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 < 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
PokerFrame (called from a viewer class) worked perfectly, but once I tried to convert it to an applet, it won't load. I don't get any runtime exceptions, just a blank applet space. I won't be able to respond/pick an answer until hours from now, but I'd really appreciate any insights anyone might have....
<HTML><head></head>
<body>
<applet code="PokerApplet.class" width="600" height="350"> </applet>
</body>
</HTML>
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class PokerApplet extends JApplet {
public void init() {
final JApplet myApplet = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel frame = new PokerFrame();
frame.setVisible(true);
myApplet.getContentPane().add(frame);
}
});
}
catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
}
import java.awt.Color;
import javax.swing.*;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.net.MalformedURLException;
/** A class that displays a poker game in a JFrame. */
public class PokerFrame extends JPanel {
public static final int HEIGHT = 350;
public static final int WIDTH = 600;
private static final int BUTTON_HEIGHT = 50;
private static final int BUTTON_WIDTH = 125;
// the following variables must be kept out as instance variables for scope reasons
private Deck deck;
private Hand hand;
private int[] handCount; // for keeping track of how many hands of each type player had
private int gamesPlayed;
private int playerScore;
private String message; // to Player
private boolean reviewMode; // determines state of game for conditional in doneBttn listener
private JLabel scoreLabel;
private JLabel gamesPlayedLabel;
private JLabel msgLabel;
private JLabel cardImg1;
private JLabel cardImg2;
private JLabel cardImg3;
private JLabel cardImg4;
private JLabel cardImg5;
/** Creates a new PokerFrame object. */
public PokerFrame() {
this.setSize(WIDTH, HEIGHT);
// this.setTitle("Poker");
gamesPlayed = 0;
playerScore = 0;
handCount = new int[10]; // 10 types of hands possible, including empty hand
message = "<HTML>Thanks for playing poker!"
+ "<br>You will be debited 1 point"
+ "<br>for every new game you start."
+ "<br>Click \"done\" to begin playing.</HTML>";
reviewMode = true;
this.add(createOuterPanel());
deck = new Deck();
hand = new Hand();
}
/** Creates the GUI. */
private JPanel createOuterPanel() {
JPanel outerPanel = new JPanel(new GridLayout(2, 1));
outerPanel.add(createControlPanel());
outerPanel.add(createHandPanel());
return outerPanel;
}
/** Creates the controlPanel */
private JPanel createControlPanel() {
JPanel controlPanel = new JPanel(new GridLayout(1, 2));
controlPanel.add(createMessagePanel());
controlPanel.add(createRightControlPanel());
return controlPanel;
}
/** Creates the message panel */
private JPanel createMessagePanel() {
JLabel msgHeaderLabel = new JLabel("<HTML>GAME STATUS:<br></HTML>");
msgLabel = new JLabel(message);
JPanel messagePanel = new JPanel();
messagePanel.add(msgHeaderLabel);
messagePanel.add(msgLabel);
return messagePanel;
}
/** Creates the right side of the control panel. */
private JPanel createRightControlPanel() {
scoreLabel = new JLabel("Score: 0");
gamesPlayedLabel = new JLabel("Games Played: 0");
JPanel labelPanel = new JPanel(new GridLayout(2, 1));
labelPanel.add(scoreLabel);
labelPanel.add(gamesPlayedLabel);
JButton doneBttn = new JButton("Done");
doneBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
class DoneListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (reviewMode) {
reviewMode = false;
startNewHand();
return;
}
else {
reviewMode = true;
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
score();
}
}
}
ActionListener doneListener = new DoneListener();
doneBttn.addActionListener(doneListener);
JPanel donePanel = new JPanel();
donePanel.add(doneBttn);
// stats button!
JButton statsBttn = new JButton("Statistics");
statsBttn.setPreferredSize(new Dimension(BUTTON_WIDTH, BUTTON_HEIGHT));
final JPanel myFrame = this;
class StatsListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// add stats pop window functionality after changing score() method to keep track of that stuff
double numGames = gamesPlayed;
String popupText = "<HTML>You've played " + gamesPlayed + " games. This is how your luck has played out:<br>"
+ "<table>"
+ "<tr><td>HAND DESCRIPTION</td>PERCENTAGE</td></tr>"
+ "<tr><td>royal flush</td><td>" + getPercentage(0) + "</td></tr>"
+ "<tr><td>straight flush</td><td>" + getPercentage(1) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(2) + "</td></tr>"
+ "<tr><td>full house</td><td>" + getPercentage(3) + "</td></tr>"
+ "<tr><td>straight</td><td>" + getPercentage(4) + "</td></tr>"
+ "<tr><td>four of a kind</td><td>" + getPercentage(5) + "</td></tr>"
+ "<tr><td>three of a kind</td><td>" + getPercentage(6) + "</td></tr>"
+ "<tr><td>two pair</td><td>" + getPercentage(7) + "</td></tr>"
+ "<tr><td>pair of jacks or better</td><td>" + getPercentage(8) + "</td></tr>"
+ "<tr><td>empty hand</td><td>" + getPercentage(9) + "</td></tr>"
+ "</table></HTML>";
JOptionPane.showMessageDialog(myFrame, popupText, "Statistics", 1);
}
private double getPercentage(int x) {
double numGames = gamesPlayed;
double percentage = handCount[x] / numGames * 100;
percentage = Math.round(percentage * 100) / 100;
return percentage;
}
}
ActionListener statsListener = new StatsListener();
statsBttn.addActionListener(statsListener);
JPanel statsPanel = new JPanel();
statsPanel.add(statsBttn);
JPanel bttnPanel = new JPanel(new GridLayout(1, 2));
bttnPanel.add(donePanel);
bttnPanel.add(statsPanel);
JPanel bottomRightControlPanel = new JPanel(new GridLayout(1,2));
bottomRightControlPanel.add(bttnPanel);
JPanel rightControlPanel = new JPanel(new GridLayout(2, 1));
rightControlPanel.add(labelPanel);
rightControlPanel.add(bottomRightControlPanel);
return rightControlPanel;
}
/** Creates the handPanel */
private JPanel createHandPanel() {
JPanel handPanel = new JPanel(new GridLayout(1, Hand.CARDS_IN_HAND));
JPanel[] cardPanels = createCardPanels();
for (JPanel each : cardPanels) {
handPanel.add(each);
}
return handPanel;
}
/** Creates the panel to view and modify the hand. */
private JPanel[] createCardPanels() {
JPanel[] panelArray = new JPanel[Hand.CARDS_IN_HAND];
class RejectListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
if (reviewMode) return;
// find out which # button triggered the listener
JButton thisBttn = (JButton) event.getSource();
String text = thisBttn.getText();
int cardIndex = Integer.parseInt(text.substring(text.length() - 1));
hand.reject(cardIndex-1);
switch (cardIndex) {
case 1:
cardImg1.setIcon(null);
cardImg1.repaint();
break;
case 2:
cardImg2.setIcon(null);
cardImg2.repaint();
break;
case 3:
cardImg3.setIcon(null);
cardImg3.repaint();
break;
case 4:
cardImg4.setIcon(null);
cardImg4.repaint();
break;
case 5:
cardImg5.setIcon(null);
cardImg5.repaint();
break;
}
}
}
ActionListener rejectListener = new RejectListener();
for (int i = 1; i <= Hand.CARDS_IN_HAND; i++) {
JLabel tempCardImg = new JLabel();
try {
tempCardImg.setIcon(new ImageIcon(new URL("http://erikaonearth.com/evergreen/cards/top.jpg")));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
String bttnText = "Reject #" + i;
JButton rejectBttn = new JButton(bttnText);
rejectBttn.addActionListener(rejectListener);
switch (i) {
case 1:
cardImg1 = tempCardImg;
case 2:
cardImg2 = tempCardImg;
case 3:
cardImg3 = tempCardImg;
case 4:
cardImg4 = tempCardImg;
case 5:
cardImg5 = tempCardImg;
}
JPanel tempPanel = new JPanel(new BorderLayout());
tempPanel.add(tempCardImg, BorderLayout.CENTER);
tempPanel.add(rejectBttn, BorderLayout.SOUTH);
panelArray[i-1] = tempPanel;
}
return panelArray;
}
/** Clears the hand, debits the score 1 point (buy in),
* refills and shuffles the deck, and then deals until the hand is full. */
private void startNewHand() {
playerScore--;
gamesPlayed++;
message = "<HTML>You have been dealt a new hand.<br>Reject cards,\nthen click \"done\"<br>to get new ones and score your hand.";
hand.clear();
deck.shuffle();
while (!hand.isFull()) {
hand.add(deck.dealCard());
}
updateCardImgs();
updateLabels();
}
/** Updates the score and gamesPlayed labels. */
private void updateLabels() {
scoreLabel.setText("Score: " + playerScore);
gamesPlayedLabel.setText("Games played: " + gamesPlayed);
msgLabel.setText(message);
}
/** Updates the card images. */
private void updateCardImgs() {
try {
String host = "http://erikaonearth.com/evergreen/cards/";
String ext = ".jpg";
cardImg1.setIcon(new ImageIcon(new URL(host + hand.getCardAt(0).toString() + ext)));
cardImg2.setIcon(new ImageIcon(new URL(host + hand.getCardAt(1).toString() + ext)));
cardImg3.setIcon(new ImageIcon(new URL(host + hand.getCardAt(2).toString() + ext)));
cardImg4.setIcon(new ImageIcon(new URL(host + hand.getCardAt(3).toString() + ext)));
cardImg5.setIcon(new ImageIcon(new URL(host + hand.getCardAt(4).toString() + ext)));
}
catch (MalformedURLException e) {
e.printStackTrace();
}
}
/** Fills any open spots in the hand. */
private void fillHand() {
while (!hand.isFull()) {
hand.add(deck.dealCard());
updateCardImgs();
}
}
/** Scores the hand.
* #return a string with message to be displayed to player
* (Precondition: hand must be full) */
private void score() {
String handScore = hand.score();
int pointsEarned = 0;
String article = "a ";
if (handScore.equals("royal flush")) {
handCount[0]++;
pointsEarned = 250;
}
else if (handScore.equals("straight flush")) {
handCount[1]++;
pointsEarned = 50;
}
else if (handScore.equals("four of a kind")) {
handCount[2]++;
pointsEarned = 25;
article = "";
}
else if (handScore.equals("full house")) {
handCount[3]++;
pointsEarned = 6;
}
else if (handScore.equals("flush")) {
handCount[4]++;
pointsEarned = 5;
}
else if (handScore.equals("straight")) {
handCount[5]++;
pointsEarned = 4;
}
else if (handScore.equals("three of a kind")) {
handCount[6]++;
pointsEarned = 3; article = "";
}
else if (handScore.equals("two pair")) {
handCount[7]++;
pointsEarned = 2;
article = "";
}
else if (handScore.equals("pair of jacks or better")) {
handCount[8]++;
pointsEarned = 1;
}
else if (handScore.equals("empty hand")) {
handCount[9]++;
article = "an ";
}
playerScore = playerScore + pointsEarned;
message = "<HTML>You had " + article + handScore + ",<br>which earned you " + pointsEarned + " points.<br>Click \"done\" to start a new hand.";
updateLabels();
}
}
I can see two weak points in your code.
First.
If your applet consists of several classes, you should add codebase attribute to your applet tag, to let it know where to find them.
For example:
<applet code="PokerApplet.class"
codebase="http://localhost/classes" width="600" height="350">
</applet>
So, in this example, your PockerApplet.class, PokerFrame.class and other used classes
should be in classes folder.
If you don't use codebase attribute, then your classes should be in the same folder where your html page with applet tag resides.
Do you consider this?
Second.
Your applet init() method seems strange. Try to use the following variant:
public void init() {
// Bad idea: the applet is not initialized yet
// but you already use link to its instance.
//final JApplet myApplet = this;
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JPanel frame = new PokerFrame();
//frame.setVisible(true); // You don't need this.
// You don't need myApplet variable
// to call getContentPane() method.
//myApplet.getContentPane().add(frame);
getContentPane().add(frame);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
You can get more help, after you add SSCCE code to your question.
first add the frame then set it to visible. THat usually works
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 < 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 < 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 < 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