Embed .swf file to my Jframe - java

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

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);
}
}

Java multithreading application game never stops/ends

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;
}
}

JPanel in JComboBox dropdown but not in the editor

What I want seems relatively simple, and I'm almost there. This will eventually be used to extend TableCellEditor, so the size is important. What I want is something like this:
With a combination of custom ComboBoxEditors and ListCellRenderers I've been able to get something like this:
Which has the inconveniences of:
Cutting off any components beyond the original width of the JComboBox
Forcing the height of the JComboBox to be the height of the JPanel in the drop-down
Allowing only one (1) click modification of the form before the drop-down disappears.
I'd like to have the drop-down stay visible until the user clicks the editor or the JComboBox looses focus to another control, and then have the value in the editor update. There will only ever be one (1) JPanel in the drop-down and I don't want the editor to be able to actually edit the string displayed.
My question is similar to #ErkanHaspalut 's question here but neither response is satisfying. I'd previously made a similar attempt by embedding a JPanel in a JPopupMenu and adding it to a JTextField but had similar issues about the popup disappearing prematurely.
I've tried forcing the size of the JComboBox both by setting the setMaximumSize height value (which has no effect) and with
Rectangle tmp = cboTest.getBounds();
tmp.height = 24;
cboTest.setBounds(tmp);
which simply shows the top 24 lines of the JComboBox. A minimum compilable example would be
/*
* Program to test having a JPanel in the JComboBox's drop-down but not the JComboBox's editor.
*/
package testdropdownsubform;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import javafx.application.Application;
import javafx.stage.Stage;
import javax.swing.ComboBoxEditor;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.JTextField;
import javax.swing.plaf.basic.BasicComboBoxEditor;
/**
* #author Masked Coder
*/
public class Dim {
public Long DimWidth;
public Long DimHeight;
public Dim () {
DimWidth = 1L;
DimHeight = 1L;
}
#Override
public String toString() {
return DimWidth.toString() + "\' x " + DimHeight.toString() + "\'";
}
}
public class DimPanel extends javax.swing.JPanel {
public DimPanel() {
spnDimWidth = new javax.swing.JSpinner();
spnDimHeight = new javax.swing.JSpinner();
spnDimWidth.setModel(new javax.swing.SpinnerNumberModel(Long.valueOf(1L), Long.valueOf(0L), null, Long.valueOf(1L)));
spnDimWidth.setPreferredSize(new java.awt.Dimension(50, 24));
addComponent(spnDimWidth);
lblTween.setText(" x ");
addComponent(lblTween);
spnDimHeight.setModel(new javax.swing.SpinnerNumberModel(Long.valueOf(1L), Long.valueOf(0L), null, Long.valueOf(1L)));
spnDimHeight.setPreferredSize(new java.awt.Dimension(50, 24));
addComponent(spnDimHeight);
}
private javax.swing.JSpinner spnDimWidth;
private javax.swing.JLabel lblTween;
private javax.swing.JSpinner spnDimHeight;
}
public class DimListCellRenderer implements ListCellRenderer {
private DimPanel dpDim;
public DimListCellRenderer(DimPanel newDimPanel) {
dpDim = newDimPanel;
}
#Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
Dim dValue = (Dim) value;
dpDim.setDim(dValue);
return dpDim;
}
}
public class DimComboBoxEditor extends BasicComboBoxEditor implements ComboBoxEditor {
JTextField txtDim = new JTextField();
Dim Item = new Dim();
public DimComboBoxEditor() {
txtDim.setEnabled(false);
txtDim.setOpaque(true);
}
#Override
public Component getEditorComponent() {
txtDim.setText(Item.toString());
return txtDim;
}
#Override
public void setItem(Object anObject) {
Item = (Dim) anObject;
}
#Override
public Object getItem() {
return Item;
}
#Override
public void selectAll() {
txtDim.selectAll();
}
#Override
public void addActionListener(ActionListener l) {
txtDim.addActionListener(l);
}
#Override
public void removeActionListener(ActionListener l) {
txtDim.removeActionListener(l);
}
}
public class MainTestForm extends javax.swing.JFrame {
public MainTestForm() {
lblPrevComponent = new javax.swing.JLabel();
chkPrevComponent = new javax.swing.JCheckBox();
lblTest = new javax.swing.JLabel();
cboTest = new JComboBox<testdropdownsubform.DicePanel>();
lblNextComponent = new javax.swing.JLabel();
scpNextComponent = new javax.swing.JScrollPane();
txaNextComponent = new javax.swing.JTextArea();
btnForceHeight = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
lblPrevComponent.setText("Prev. Component");
chkPrevComponent.setText("jCheckBox1");
lblTest.setText("Dimension");
cboTest.setEditable(true);
cboTest.setEditor(new DimComboBoxEditor());
cboTest.setRenderer(new DimListCellRenderer(new DimPanel()));
cboTest.addItem(new Dim());
lblNextComponent.setText("Next Component");
txaNextComponent.setColumns(20);
txaNextComponent.setRows(5);
scpNextComponent.setViewportView(txaNextComponent);
btnForceHeight.setText("Force");
btnForceHeight.setToolTipText("Force test combobox height");
btnForceHeight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnForceHeightActionPerformed(evt);
}
});
.addComponent(lblPrevComponent)
.addComponent(chkPrevComponent))
.addComponent(lblTest)
.addComponent(cboTest)
.addComponent(lblNextComponent)
.addComponent(scpNextComponent)
.addComponent(btnForceHeight))
}
private void btnForceHeightActionPerformed(java.awt.event.ActionEvent evt) {
Rectangle tmp = cboTest.getBounds();
tmp.height = 24;
cboTest.setBounds(tmp);
}
/**
* #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 MainTestForm().setVisible(true);
}
});
}
private javax.swing.JButton btnForceHeight;
private javax.swing.JComboBox cboTest;
private javax.swing.JCheckBox chkPrevComponent;
private javax.swing.JLabel lblNextComponent;
private javax.swing.JLabel lblPrevComponent;
private javax.swing.JLabel lblTest;
private javax.swing.JScrollPane scpNextComponent;
private javax.swing.JTextArea txaNextComponent;
}
public class TestDropdownSubform extends Application {
#Override
public void start(Stage primaryStage) {
MainTestForm mtfMain = new MainTestForm();
mtfMain.setVisible(true);
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
My question is, am I missing a detail, or can anyone see a better way to accomplish this? Thanks in advance for your advice.
Edit: Declaring the JComboBox as
JComboBox cboTest = new JComboBox<DimPanel>() {
private boolean layingOut = false;
#Override
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
#Override
public Dimension getSize(){
Dimension dim = super.getSize();
if(!layingOut) {
dim.width = Math.max(dim.width, dpThis.getPreferredSize().width);
}
return dim;
}
};
fixes the width of the drop-down. Declaring it as
JComboBox cboTest = new JComboBox<testdropdownsubform.DicePanel>() {
private boolean layingOut = false;
#Override
public void doLayout(){
try{
layingOut = true;
super.doLayout();
}finally{
layingOut = false;
}
}
#Override
public Dimension getSize(){
Dimension dim = super.getSize();
if(!layingOut) {
Dimension dim2 = dpThis.getPreferredSize();
dim.width = Math.max(dim.width, dim2.width);
// dim.height = dim2.height;
}
return dim;
}
#Override
public DimPanel getPrototypeDisplayValue() {
DimPanel tmpPanel = new DimPanel();
if(isCalledFromComboPopup()) {
//
}
else {
Dimension r = dcbeEditor.getPreferredSize();
tmpPanel.setPreferredSize(r);
}
return tmpPanel;
}
/**
* Hack method to determine if called from within the combo popup UI.
*/
public boolean isCalledFromComboPopup() {
try {
final Throwable t = new Throwable();
t.fillInStackTrace();
StackTraceElement[] st = t.getStackTrace();
// look only at top 5 elements of call stack
int max = Math.min(st.length, 5);
for (int i=0; i<max; ++i) {
final String name = st[i].getClassName();
System.out.println(i + ") " + name);
return ((name != null) && name.contains("ComboPopup"));
}
} catch (final Exception e) {
// if there was a problem, assume not called from combo popup
}
return false;
}
};
fixes the editor size but now the drop-down is the width and height of the editor.
So, I ended up going on a different track, creating my own pseudo-combobox with a JTextField and a JButton in a JPanel. I believe I've quite handily genericized the result into four related classes. First, you need an implementation of AbstractPopupPanel (which quite handily loads into the NetBeans designer if you're using it):
package complexcombobox;
/**
*
* #author MaskedCoder
*
* #param E - the object to be edited in the panel
*/
public abstract class AbstractPopupPanel<E> extends javax.swing.JPanel {
/**
* Creates new form PopupPanel
*/
public AbstractPopupPanel() {
initComponents();
}
public abstract boolean isChanged();
public abstract E getValue();
public abstract void setValue(E newValue);
private void initComponents() {
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}
}
With that created to your satisfaction, we need to place it in a pop-up menu:
package complexcombobox;
import javax.swing.JPopupMenu;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
/**
*
* #author MaskedCoder
*
* #param E - the object to be edited
* #param P - the extension of AbstractPopupPanel that will display the object as you wish
*/
public class ComplexPopup<E, P extends AbstractPopupPanel<E>> extends JPopupMenu {
/*
* Interface to notify user of editing
*/
public interface EditListener<E> {
// return the object's value to be edited.
// if the user returns null, the existing Dice is used.
public E beforeEdit();
// receives the new value
// called *only* when the object has actually changed.
public void afterEdit(E newValue);
}
/*
*internal variables
*/
private P thisPanel;
private EditListener<E> userListener;
// private Class<E> eClass;
// private Class<P> pClass;
private PopupMenuListener myPopupListener = new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
if(userListener != null) {
E tmpSize = userListener.beforeEdit();
if(tmpSize != null) thisPanel.setValue(tmpSize);
}
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
if(userListener != null) {
// if(thisPanel.isChanged())
userListener.afterEdit((E) thisPanel.getValue());
}
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
popupMenuWillBecomeInvisible(e);
}
};
/*
* Constructors
*/
public ComplexPopup(E iniValue, P iniDropdownPanel, EditListener<E> iniListener) {
super();
init(iniValue, iniDropdownPanel, iniListener);
}
private void init(E iniValue, P iniDropdownPanel, EditListener<E> iniListener) {
thisPanel = iniDropdownPanel;
thisPanel.setValue(iniValue);
add(thisPanel);
userListener = iniListener;
this.addPopupMenuListener(myPopupListener);
}
/*
* Public Properties
*/
public E getValue() {
return (E) thisPanel.getValue();
}
public void setValue(E newObjectSize) {
thisPanel.setValue(newObjectSize);
}
public EditListener getUserListener() {
return userListener;
}
public void setEditListener(EditListener newListener) {
userListener = newListener;
}
/*
* functional extensions
*/
public void afterEdit(E newValue) {
if(userListener != null) {
if(thisPanel.isChanged())
userListener.afterEdit((E) thisPanel.getValue());
}
}
}
This places the form in a JPopupMenu and allows access to the object to be edited as well as notification before and after editing. Now, I couldn't co-opt the JComboBox interface without getting deeper into the mechanics than I wanted to go, so I fudged the combo box, as I mentioned:
package complexcombobox;
/**
*
* #author MaskedCoder
*
* #param <I> the Item (Object) to be edited
* #param <Q> the AbstractPopupPanel to be used to do the editing.
*/
public class ComplexComboBox<I, Q extends AbstractPopupPanel<I>> extends javax.swing.JPanel {
private ComplexPopup<I, Q> thePopup;
private ComplexPopup.EditListener<I> myListener = new ComplexPopup.EditListener<I>() {
#Override
public I beforeEdit() {
return null; // no changes so, just let it ride.
}
#Override
public void afterEdit(I newValue) {
txtEditor.setText(thePopup.getValue().toString());
}
};
/**
* Creates new form ObjectSizeComboBox
*/
public ComplexComboBox(I iniValue, Q iniPanel) {
initComponents();
thePopup = new ComplexPopup<I, Q>(iniValue, iniPanel, myListener);
}
public I getValue() {
return thePopup.getValue();
}
public void setValue(I newValue) {
thePopup.setValue(newValue);
}
private void initComponents() {
txtEditor = new javax.swing.JTextField();
btnShowPanel = new javax.swing.JButton();
setBackground(new java.awt.Color(255, 255, 255));
setMinimumSize(new java.awt.Dimension(40, 19));
txtEditor.setEditable(false);
txtEditor.setToolTipText("");
txtEditor.setOpaque(false);
btnShowPanel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/testpopupsubform/art/dropdownarrow.png"))); // NOI18N
btnShowPanel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnShowPanelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(txtEditor, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE)
.addGap(1, 1, 1)
.addComponent(btnShowPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnShowPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(txtEditor)
);
}
private void btnShowPanelActionPerformed(java.awt.event.ActionEvent evt) {
thePopup.show(txtEditor, 0, txtEditor.getHeight());
}
private javax.swing.JButton btnShowPanel;
private javax.swing.JTextField txtEditor;
}
This seems to work very well in a cell editor for a table, provided you make the row heights tall enough. That's no different than a regular JComboBox editor, though:
package complexcombobox;
import java.awt.Component;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
/**
*
* #author MaskedCoder
*
* #param <E> the Element (Object) to be edited
* #param <P> the AbstractPopupPanel to be used to do the editing.
*/
public class ComplexCellEditor<E, P extends AbstractPopupPanel<E>> extends AbstractCellEditor
implements TableCellEditor {
private ComplexComboBox<E, P> ComplexEditor;
/*
* Constructors
*/
public ComplexCellEditor(E iniValue, P iniPanel) {
super();
ComplexEditor = new ComplexComboBox<E, P>(iniValue, iniPanel);
}
/*
* AbstractCellEditor Extensions
*/
#Override
public boolean stopCellEditing() {
return super.stopCellEditing();
}
/*
* TableCellEditor Implementation
*/
#Override
public E getCellEditorValue() {
return ComplexEditor.getValue();
}
#Override
public Component getTableCellEditorComponent(JTable iniTable, Object iniValue, boolean isSelected, int row, int column) {
ComplexEditor.setValue((E) iniValue);
return ComplexEditor;
}
}
Three things I'm not entirely satisfied with:
- I'd like to grab the JComboBox down-arrow icon from the system rather than relying on a project resource
- I've had to pass through the AbstractPopupPanel instance which means that the coder has to create the panel themselves and then hand it to the constructor for ComplexComboBox or ComplexCellEditor. I'd rather have created the panel internally, in ComplexPopup and managed it myself. I ran into difficulty instantiating Generic constructors. Pass-through does allow the coder more control but I don't think that's needed and I'd like it to be optional at least.
My knowledge of Generics isn't advanced but this seems to do the trick.

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

Is it possible to detect window occlusion

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;
}
}
}
}

Categories