Pixel Listener (Listener reacting on Pixel changes) - listener

i want to create a program that is reacting on some pixels and is increasing a counter when a selected pixel is changed.
Im using the Robot class for it. cause this:
Boolean dontcount = false;
Robot robot = new Robot();
while (true) {
if(robot.getPixelColor(900, 900).equals(b)){
if(dontcount == false){
counter=counter++;
dontcount = true;
System.out.println(counter);
}
} else {
dontcount = false;
}
}
is killing my pc, i am looking for another way. I guess its possible with listeners. but i got no idea how. any solutions?

Your code does not compile and doesn't seem to make much sense so I rewrote it. In the future, make sure you have a complete example.
The reason the code is killing your PC is because you should be putting a slight wait time in your while loop to let the computer know it has a chance to breathe. 10ms is plenty.
import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;
public class Main
{
public static void main(String[] args)
{
Robot robot = null;
try
{
robot = new Robot();
} catch (AWTException e1)
{
e1.printStackTrace();
}
Color lastPixelColor = null;
int counter = 0;
while (true)
{
Color pixelColor = robot.getPixelColor(900, 900);
if (!pixelColor.equals(lastPixelColor))
{
counter++;
System.out.println(counter);
}
lastPixelColor = pixelColor;
try
{
// You need to sleep so you don't murder your CPU
Thread.sleep(10);
} catch (InterruptedException e)
{
}
}
}
}

Related

LibGDX - Splash Screen timer isn't working

I want a timer that switches screens after a certain amount of time. Here is the code for my splash screen:
private boolean timerIsOn = false;
And here is the render() method code:
if(!timerIsOn) {
timerIsOn = true;
Timer.*schedule*(new Task() {
#Override
public void run() {
*changeScreen*();
}
}, 15);
} else if(Gdx.input.isTouched()) {
// Remove the task so we don't call changeScreen twice:
Timer.instance().clear();
*changeScreen*();
}
}
I'm getting red swiggly lines under the parts of the code that have * and * surrounding them but the suggested action to fix it doesn't help.
Also, if you know of an easier way to make this work or possibly a tutorial that would be great as well.

WP8 - How can I make the background agent execution to wait before all ImageOpened events are fired to update live tile with custom images?

How can I make the background agent execution to wait before all ImageOpened() events are fired (3 in this case) in order to update secondary live tile with custom images?
Edit 1:
In the OnInvoke() method of the ScheduledAgent I am calling my own create tile data function implemented in a shared library which in turn subscribes to 3 ImageOpened() events as I am trying to create custom images for all live tile templates i.e. small, medium and wide.
Since these being asynchronous events I have no way to check if all the events have completed successfully so that I can call NotifyComplete() to notify the background agent that its job is now done. So sometimes the tile gets updated while most of the times it doesn't. Also I am using the same function to update the live tiles every time the app is launched so there is no problem with its implementation. I have also tried to take care of all the memory limitations with the ScheduledAgent by disposing Bitmaps and calling GC.Collect() forcefully.
Please help in any possible way to fix this problem.
Add a new class that lets you create custom events -
public class SaveImageCompleteEventArgs : EventArgs
{
public bool Success { get; set; }
public Exception Exception { get; set; }
public string ImageFileName { get; set; }
public SaveImageCompleteEventArgs(bool success, string fileName)
{
Success = success;
ImageFileName = fileName;
}
}
Initialize the events and required variables in the file you are updating the custom live tile from -
public static int countTile = 3;
public event EventHandler<SaveImageCompleteEventArgs> SaveMediumImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveWideImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveSmallImageComplete;
public event EventHandler<SaveImageCompleteEventArgs> SaveAllImagesComplete;
Fire the completion event in the ImageOpened() event handlers for all the tiles and check if the SaveAllImagesComplete event needs to be fired-
public void OnBackgroundBmpOpenedMedium(object sender, RoutedEventArgs e)
{
if (SaveMediumImageComplete != null)
{
countTile -= 1;
CheckIfAllImagesOpened();
SaveMediumImageComplete(this, new SaveImageCompleteEventArgs(true, mediumTileImageUriIronMan));
}
}
private void CheckIfAllImagesOpened()
{
if (countTile == 0)
{
if (SaveAllImagesComplete != null)
{
var args1 = new SaveImageCompleteEventArgs(true, "");
SaveAllImagesComplete(this, args1);
}
}
}
In the ScheduledAgent file -
public static ManualResetEvent evt;
public bool IsPaused { get { return !evt.WaitOne(0); } }
In the OnInvoke() function -
evt = new ManualResetEvent(false);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
//Initialize secondary tile here
if (secondaryTile != null)
{
/*
obj is a object of a helper file that contains all the
functions responsible for updating the custom live tile
Call the function that is responsible for initializing all the
tile image bitmpas and that subscribes to the ImageOpened events
*/
obj.SaveMediumImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveWideImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveSmallImageComplete += async (s, args) =>
{
if (!IsPaused)
evt.Set();
};
obj.SaveAllImagesComplete += async (s, args) =>
{
try
{
if (args.Success)
obj.UpdateTileIcon();
}
catch (Exception) { }
finally
{
if (!IsPaused)
evt.Set();
}
};
}
});
evt.WaitOne();
NotifyComplete();

Best way to get a variable from another class in AS3

I wonder which one of these methods is the best when trying get a variable from anotherClass to the Main-document-class, and why? Are there any more, even better ways?
In example no 1, and the Main-function, can the if-else statement be triggered before the checkLogin function was completely done? Thanks!
My no 1. way
public class Main extends MovieClip {
// Declaring other classes.
private var checkLogin:CheckLogin;
public function Main() {
checkLogin = new CheckLogin();
if(checkLogin.isLoggedIn == true) {
trace("Is logged in");
} else {
trace("Not logged in");
}
}
}
and
public class CheckLogin {
public var isLoggedIn:Boolean;
public function CheckLogin() {
isLoggedIn = false;
}
}
Or is it a lot better to do it this way,
(Way no 2):
public class Main extends MovieClip {
// Declaring other classes.
private var checkLogin:CheckLogin;
public function Main() {
checkLogin = new CheckLogin();
checkLogin.addEventListener("checkLogin.go.ready", checkLoginReady);
checkLogin.go();
}
public function checkLoginReady(event = null) {
if(checkLogin.isLoggedIn == true) {
trace("Is logged in");
} else {
trace("Not logged in");
}
}
}
and
public class CheckLogin extends EventDispatcher {
public var isLoggedIn:Boolean;
public function CheckLogin() {
isLoggedIn = true;
}
public function go() {
this.dispatchEvent(new Event("checkLogin.go.ready"));
}
}
Generally, using events will make your code easier to maintain.
The login check you describe seems to be instant, so approach number 1 would be ok for such a simple case.
Often the login check (or whatever process) may not be instant, for example if the CheckLogin class sent a server request and waited for the response. In this case using events is better. The Main class can listen for a LOGIN_SUCCESS or LOGIN_FAIL event and handle it when the event occurs. All the login logic stays within CheckLogin.
Also, using events will allow multiple interested classes to react, without them knowing any of the inside login process.

JTree and dropdown options on right clicking nodes

I'm trying to use the JTree and implement different drop downs for all the parent nodes and the children nodes.
Here's what I've done:
pmTree.addMouseListener(new java.awt.event.MouseAdapter() {
#Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
try {
if(evt.getButton() == evt.BUTTON1) {
}
else if (evt.getButton() == evt.BUTTON3) {
TreePopup(evt);
//pmTree.updateUI();
}
}catch (Exception e) {}
}
});
and PopupCode:
public void TreePopup(java.awt.event.MouseEvent evt) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) pmTree.getLastSelectedPathComponent();
popup = new JPopupMenu();
popup.setInvoker(pmTree);
PopupHandler handler = new PopupHandler(pmTree, popup);
if(node.getLevel() == 1)
{
popup.add(getMenuItem("Parent Node", handler));
}
else if(node.getLevel() == 2)
{
popup.add(getMenuItem("Child", handler));
}
}
and PopUpHandler:
public class PopupHandler extends javax.swing.JFrame implements ActionListener {
JPopupMenu popup;
Point loc;
public PopupHandler(JTree tree, JPopupMenu popup) {
//this.tree = NewJFrame.pmTree;
this.popup = popup;
tree.addMouseListener(ma);
}
and also the
public void actionPerformed(java.awt.event.ActionEvent evt)
for the Child or Parent node being clicked.
However, when I run the program, I get the SAME right click popups for both the child and parent node.
Sorry for the huge chunk of code. I've been stuck with it for 2 days and yet not successful.
Thanks!
Don't go as low-level as a MouseListener, instead use the api around componentPopupMenu. Doing so, the general approach is dynamically configure the componentPopup in the getPopupLocation method, some simple example snippet:
JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {
/**
* #inherited <p>
*/
#Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
// here do your custom config, like f.i add/remove menu items based on context
// this example simply changes the action name
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}
};
tree.setComponentPopupMenu(popup);
You check the selected node:
DefaultMutableTreeNode node = (DefaultMutableTreeNode)pmTree.getLastSelectedPathComponent();
to see if you have a "parent" or a "child" node. You should select the node at the mouse position first, otherwise it will not be the right node. Call
TreePath path = pmTree.getPathForLocation(evt.getX(), evt.getY());
if (path != null) {
pmTree.setSelectionPath(path);
} else {
return;
}
at the beginning of treePopup. (methods in Java should start with a lower case letter!)
Awesome. I was successfully able to put the setSelectionPath() call inside the override of getPopupLocaiton(). I had been trying to do it inside the ActionListener of my JMenuItem to no avail.
public Point getPopupLocation( MouseEvent e ) {
Point point = null;
if( e != null ) {
TreePath path = getClosestPathForLocation( e.getX(), e.getY() );
setSelectionPath( path );
point = e.getPoint();
}
return point;
}

In flash AS3 How to put single try catch code, in order to catch any errors in whole class?

In Flash AS3 I wanna write the single try catch block in order to catch any errors in whole class.
For example, I have a lot of functions in myClass.as. I don't wanna write in each function try catch blocks in order to catch errors in this function.
Is there any methods to do this?
Thank you!
you can't! there is no such easy way like that even in other language either than AS3 except they use AOP approach to do that.
The best practice is just let you classes bubble the Error (Exception) and let the higher layer catch and process the error.
EDIT - regarding coment
Actually the idea is the natural way.. still you need to manually catch every possible error. i'll give you example. Note that the purpose of the example only for clarity between lower layer and higher layer.
for example you have a class in the mid layer (Your Business Process):
public class MyBussiness {
public function loadImages(){
//for example here is a block of method
//possibly throws exception.
}
public function getLoan(){
//lets assume here too
}
}
in the higer layer (I Assume in your View - MXML) you catch the exception like bellow:
var myBussiness:MyBussiness = new MyBussiness():
try {
myBussiness.loadImages();
//any other sequence process
myBussiness.getLoan();
}
catch(error:Error){
//here you process error
//show it to user or make LOG
}
still it can't do a magic like you expect but it is the best practice. Rember only put try catch only on code that has possibility to throw error because try catch is expensive.
The best way is using try catch:
try{
//your command
} catch(e:Error){
//your command
}
You can catch all not handled errors in your program by using UncaughtErrorEvent class.
So, may be it what you want. There is an example from the docs (you could place addEventListener in the constructor of your main class):
package
{
import flash.display.Sprite;
import flash.events.ErrorEvent;
import flash.events.MouseEvent;
import flash.events.UncaughtErrorEvent;
public class UncaughtErrorEventExample extends Sprite
{
public function UncaughtErrorEventExample()
{
loaderInfo.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, uncaughtErrorHandler);
drawUI();
}
private function uncaughtErrorHandler(event:UncaughtErrorEvent):void
{
if (event.error is Error)
{
var error:Error = event.error as Error;
// do something with the error
}
else if (event.error is ErrorEvent)
{
var errorEvent:ErrorEvent = event.error as ErrorEvent;
// do something with the error
}
else
{
// a non-Error, non-ErrorEvent type was thrown and uncaught
}
}
private function drawUI():void
{
var btn:Sprite = new Sprite();
btn.graphics.clear();
btn.graphics.beginFill(0xFFCC00);
btn.graphics.drawRect(0, 0, 100, 50);
btn.graphics.endFill();
addChild(btn);
btn.addEventListener(MouseEvent.CLICK, clickHandler);
}
private function clickHandler(event:MouseEvent):void
{
throw new Error("Gak!");
}
}
}
See the docs, please.