Java: change variable from outside while looping through a while queque - variables

I am a Java Beginner and have a little question.
I have got 2 Classes:
the first one is a java formular, the important code is:
#Override
public void keyPressed(KeyEvent event) {
int key = event.getKeyCode();
if(key == 17) {
System.out.println("STRG");
if(roboter.running == true) {
roboter.running = false;
}
}
}
the second one is a class (called robot) which main part is the for loop:
public class Roboter {
public boolean running = false;
public void myFunction() {
for(...;...;...) {
for(...;...;...) {
if(!running)
break;
// DO SOMETHING IMPORTANT
}
}
}
Well, this doesn't work. I think it is because I can't change the value of running while my for loop. I have no idea how to slove this problem. Maybe there is an other solution? My aim is to stop the robots myFunction if an user press a key.I hope you can help me
I am sorry for my english, if you don't undestand me I will try to rewrite the question.

The class that handles the keyboard input should run in a separate Thread.

Related

Haxe+OpenFL->Neko, MouseEvent.xxxKey always false

I am making a game using Haxe+OpenFL. I had targeted js once ago, then I switched to neko and the following construction stopped working:
if(e.shiftKey)
do smth
Ofc I've not changed this block of code, nor context since changing the target. What has gone wrong?
P. S. Tracing shows, that holding alt, ctrl or shift keys do not change corresponding properties of MouseEvent object
Based on this link, it used to be a problem, but has been fixed two years ago. Strangely, my tests show it still doesn't work.
This class demonstrates that it will work correctly in js but not in neko.
class Main extends Sprite
{
public function new()
{
super();
var s:Sprite = new Sprite();
s.graphics.beginFill(0xff0000);
s.graphics.drawCircle(100, 100, 200);
s.graphics.endFill();
addChild(s);
//testing a simple click event
s.addEventListener(MouseEvent.CLICK, OnClick);
//testing wheel events, as I read somewhere it could a been a bug in earlier versions
s.addEventListener(MouseEvent.MOUSE_WHEEL, OnWheel);
//testing click events on the stage object, in case it acted differently
addEventListener(MouseEvent.CLICK, OnStageClick);
}
private function OnStageClick(e:MouseEvent):Void
{
trace(e.shiftKey);
}
private function OnWheel(e:MouseEvent):Void
{
trace(e.shiftKey);
}
private function OnClick(e:MouseEvent):Void
{
trace(e.shiftKey);
}
}
An alternative solution could be to use openfl.events.KeyboardEvent and note when the shift key is up or down as a boolean (note that shift's keycode is 16). This example works correctly in my tests.
class Main extends Sprite
{
var shiftIsPressed:Bool = false;
public function new()
{
super();
stage.addEventListener(KeyboardEvent.KEY_DOWN, OnDown);
stage.addEventListener(KeyboardEvent.KEY_UP, OnUp);
stage.addEventListener(MouseEvent.CLICK, OnClick);
}
private function OnUp(e:KeyboardEvent):Void
{
if (e.keyCode == 16)
{
shiftIsPressed = false;
}
}
private function OnDown(e:KeyboardEvent):Void
{
if (e.keyCode == 16)
{
shiftIsPressed = true;
}
}
private function OnClick(e:MouseEvent):Void
{
if (shiftIsPressed)
{
trace('Click!');
}
}
}
Update
Since I've always used the keyboard event trick I mentioned earlier, I missed the fact that it also does not work in C++. I suppose those two targets use some custom event system and someone forgot to register the modifier keys to the created event.
Update 2 (sept 22)
Someone fixed it

Mockito.doNothing() is still running

I'm trying to test small pieces of code. I do not want test one of the method and used Mockito.doNothing(), but this method was still run. How can I do that?
protected EncoderClientCommandEventHandler clientCommandEventHandlerProcessStop = new EncoderClientCommand.EncoderClientCommandEventHandler() {
#Override
public void onCommandPerformed(
EncoderClientCommand clientCommand) {
setWatcherActivated(false);
buttonsBackToNormal();
}
};
protected void processStop() {
EncoderServerCommand serverCommand = new EncoderServerCommand();
serverCommand.setAction(EncoderAction.STOP);
checkAndSetExtension();
serverCommand.setKey(getArchiveJobKey());
getCommandFacade().performCommand(
serverCommand,
EncoderClientCommand.getType(),
clientCommandEventHandlerProcessStop);
}
#Test
public void testClientCommandEventHandlerProcessStop() {
EncoderClientCommand encoderClientCommand = mock(EncoderClientCommand.class);
Mockito.doNothing().when(encoderCompositeSpy).buttonsBackToNormal();
when(encoderCompositeSpy.isWatcherActivated()).thenReturn(false);
encoderCompositeSpy.clientCommandEventHandlerProcessStop.onCommandPerformed(encoderClientCommand);
I've found the problem. One of the variable is already mocked in buttonsBackNormal().

Chain of Responsibility Design Pattern

I want to get an intuitive feeling for Chain of Responsibility pattern. I guess a good way to get that would be to learn about some real world examples. Can you guys share such examples?
One of the things about this pattern is that if the chain has many stages, lets say more than 10, implementation gets quite ugly. What do you guys do about that?
I think the Servlet filters are a good example. The chain is built for you and you can decide to call the next one. However the construction/wiring is done for you here.
If the 10 is hairy you can simplify with a builder:
interface ChainElement {
void setNext(ChainElement next);
void doSomething();
}
class ChainBuilder {
private ChainElement first;
private ChainElement current;
public ChainBuilder then(ChainElement next) {
if (current == null) {
first = current = next;
} else {
current.setNext(next);
current = next;
}
return this;
}
public ChainElement get() {
return first;
}
}
Then at construction:
ChainElement chain = new ChainBuilder()
.then(new FirstElement())
.then(new SecondElement())
.then(new ThirdElement())
.get();
chain.doSomething();

EasyMock Testing Void With Runnable

I'm trying to test the following class (I've left out the implementation)
public class UTRI implements UTR {
public void runAsUser(String userId, Runnable r);
}
This is the way I would use it:
UTRI.runAsUser("User1", new Runnable () {
private void run() {
//do whatever needs to be done here.
}
});
The problem is, I don't know how to use EasyMock to test functions that return void. That and I'm also not too familiar with testing in general (right out of school!). Can someone help explain to me what I need to do to approach this? I was thinking about making the UTRI a mock and doing expectlastcall after that, but realistically, not sure.
public class UTRITest {
UTRI utri = new UTRI();
#Test
public void testRunAsUser() {
// Create Mocks
Runnable mockRunnable = EasyMock.createMock(Runnable.class);
// Set Expectations
**mockRunnable.run();
EasyMock.expectLastCall().once();**
EasyMock.replay(mockRunnable);
// Call the method under test
utri.runAsUser("RAMBO", **mockRunnable**);
// Verify if run was called on Runnable!!
EasyMock.verify(mockRunnable);
}
}

MVVM-Light and WP7 ViewModel tombstoning isn't working

I've tried following the steps in Joost Van Schaik's article on tombstoning but was unable to get it to work for me. I'm no doubt doing something wrong. In my ViewModel:
private string _foobar ="init";
public string testStr
{
get
{
return _foobar;
}
set
{
_foobar = value;
}
}
And in my page:
<TextBox x:Name="tBoxTest" Text="{Binding testStr, Mode=TwoWay}" />
While the application is running, changing the value in tBoxTest sets _foobar just fine, but try to serialize it and it’s as if it has forgotten the instance??? Any help would be greatly appreciated.
I was able to get tombstoning to work, along with having an object be visible to all my ViewModels, by doing the following:
In a Model class, I added:
private static Model1 _instance;
public static Model1 Instance
{
get { return _instance; }
set { _instance = value; }
}
public static void CreateNew()
{
if (_instance == null)
{
_instance = new Model1();
_instance.FirstString = "init";
}
}
Then in ApplicationExtensions.cs I added:
public static void SaveToIsolatedStorage(this Application app, Model1 model)
{
var dataFileName = GetIsFile((model.GetType()));
using (var userAppStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (userAppStore.FileExists(dataFileName))
{
userAppStore.DeleteFile(dataFileName);
}
using (var iss = userAppStore.CreateFile(dataFileName))
{
SilverlightSerializer.Serialize(model, iss);
}
}
}
And in App.xaml.cs I changed LoadModel() to:
private void LoadModel()
{
try
{
Model1.Instance = this.RetrieveFromIsolatedStorage<Model1>();
}
catch (Exception) { }
if (Model1.Instance == null) Model1.CreateNew();
}
That all made things like this work in my ViewModel files:
public string TestStr
{
get
{
return Model1.Instance.FirstString;
}
set
{
Model1.Instance.FirstString = value;
}
}
And by that, I mean that the Model1 object is getting serialized and tombstoning is working - at least I’m getting what I think I want. I’ve tested it a lot by navigating between apps, phone settings, turning the phone off and on, locking it and calling it while in the app from another phone. Performance when deserializing is great. And I can work with the vars.
That said, Mr. Van Schaik replied to a request for assistance with: "If you are subclassing from an MVVMLight ViewModelBase it does, and then you should call RaisePropertyChanged from your setter like this:
private string _foobar ="init";
public string TestStr
{
get
{
return _foobar;
}
set
{
RaisePropertyChanged("TestStr");
_foobar = value;
}
}
RaisePropertyChanged notifies any listenings views (i.e. the TextBox you bound to it) that a property is changed and that the should update their contents. This is a crucial mechanism."
So I will work with what I was originally trying but with the addition of RaisePropertyChanged to see what that does.
UPDATE
Although I implemented RaisedPropertyChanged (using the code snippet mvvminpc) in my MainViewModel.cs file, that still had no effect (as good as it may be for other things) on serializing anything created within the ViewModel. I'm probably still doing something wrong, but it may also be because view models inherit from a protected class (answer from Laurent Bugnion). I (very reluctantly) tried changing that class from protected to public and recompiling, but it didn't help in my case and I hate to fork a referenced library like that. Anyway, I'm just forging ahead for now with creating the Model1 instance in App.xaml.cs. Seems to work. While I was at it, I modified one of Van Schaik's methods to accept any type of object:
public static void SaveToIsolatedStorage<T>(this Application app, T obj)
where T : class
{
var dataFileName = GetIsFile(typeof(T));
using (var userAppStore =
IsolatedStorageFile.GetUserStoreForApplication())
{
if (userAppStore.FileExists(dataFileName))
{
userAppStore.DeleteFile(dataFileName);
}
using (var iss = userAppStore.CreateFile(dataFileName))
{
SilverlightSerializer.Serialize(obj, iss);
}
}
}
From the code you've posted there isn't an instant answer.
My advice to debug this is:
if you've copied the code exactly from that article then add something (a messagebox?) to the empty catch handler - `catch (Exception){ }
use the debugger to put breakpoints in the LoadModel and SaveToIsolatedStorage methods
use these breakpoints to step through the Load and Save code - is the code correctly loading and saving?
To be honest, with problems like this, doing a little investigation yourself is much better than asking questions on here (IMO!)