how to invoke an event on a key press - graphics

I am making a gambling game in graphics. There are three polygons on screen reading below 3, above 3 and throw a dice. I will incorporate random function generator in throw a dice area. And define two functions when a user enters the area of the rest of two polygons. But I am facing the problem of how to add functions here and how to invoke those function on keypress. Please suggest.

I think should have mentioned the language you are using to code, In case of java swing i have a good solution.
Depending on where you want to trap the "enter" key, you could use an ActionListener (on such components such as text components or buttons) or attach a key binding to your component.
Here is the link how to use Key binding
public class MyPanel extends JPanel {
public MyPanel() {
InputMap im = getInputMap(WHEN_FOCUSED);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onEnter");
am.put("onEnter", new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
// Enter pressed
}
});
}
}
Actually i didn't understand your question, secondly if you are trying to nesting the events you can use threading i have link --Threading with swing.
you can check your question context here and apply it.
Ok and this is all for java, if you are working with other prog. language then please comment.
Thanks..

Related

JavaFX: Autoscroll of TextArea with appendText but without Listeners

I've read the other articles on Stackoverflow on this topic. But none of them matches my problem exactly.
I want to log an algorithm in a TextArea. In each iteration of the algorithm the text in this TextArea should be expanded via appendText().
My first problem is: Where should I create the new Thread and how can the both threads communicate with each other (GUI and algorithm)?
In my actual design I have three important classes: The view, which holds the TextArea, the controller, which calls the algorithm and the algorithm, which takes a number of iterations and the TextArea (to call the appendText()-method on severage places in the code).
In this design the controller calls the algorithm, the algorithm iterates n times with a for-loop and after it terminates, the GUI shows the changes. But I want the GUI to show the changes simultaneously, when the algorithm calls the appendText()-method.
And my second problem is the autoscroll of the TextArea. After each appendText-call the TextArea should be scrolled completely down. But I think the solution of this problem is the same solution of my first problem.
I would be very grateful for some help.
It's pretty much impossible to answer your question completely without (a lot) more information, but the general approach I would use would be for the algorithm to have a callback to process a message, which could be invoked by each step of the algorithm. From the controller, pass an implementation of the callback which updates the text area with the message, on the FX Application Thread.
Something like:
public class Algorithm {
private Consumer<String> statusCallback ;
public Algorithm(Consumer<String> statusCallback) {
this.statusCallback = statusCallback ;
}
public Algorithm() {
// by default, callback does nothing:
this(s -> {});
}
public void performAlgorithm() {
while (! finished() ) {
doNextStep();
String statusMessage = getStatus();
statusCallback.accept(statusMessage);
}
}
}
and then
public class Controller {
private View view = ... ;
public void startAlgorithm() {
Algorithm algorithm = new Algorithm(s -> Platform.runLater(view.appendStatus(s)));
Thread t = new Thread(algorithm::performAlgorithm);
t.setDaemon(true);
t.start();
}
}
For the View you then do the following (note that you can scroll down with textArea.setScrollTop(Double.MAX_VALUE);):
public class View {
private TextArea textArea ;
public View() {
textArea = new TextArea();
// ...
}
public void appendStatus(String status) {
if (!textArea.getText().isEmpty()) {
textArea.appendText("\n");
}
textArea.appendText(status);
textArea.setScrollTop(Double.MAX_VALUE);
}
}
This should work as long as your algorithm doesn't create too many status updates too fast (so that they flood the FX Application Thread and prevent it doing its normal work).

HaxeFlixel - FlxSubState unexpected null object reference

Im trying to make simple ingame menu. Im using FlxSubState class. First im trying invoke substate in main game state with openSubState(gameMenu); after pressing Esc.
There is code in my substate class, this class inheriting FlxSubState:
override public function create():Void
{
super.create();
continueButton = new FlxButton(0,0, "Continue", continueGame);
continueButton.x = FlxG.width / 2 - continueButton.width / 2;
continueButton.y = FlxG.height / 2 - continueButton.height / 2;
add(continueButton);
}
private function continueGame():Void
{
close();
}
Problem is : everytime after click on continueButton game crash with null exception in FlxTypedGroup. I think its in close(); method but i really cannot figure it out. Can anyone help me ?
Or suggest better way to implement ingame menu ?
Figured it out by myself.
Looks like that after closing substate is destroyed. So something like this
override public function create():Void
{
super.create();
gameMenu = new MySubstate();
}
using with this
openSubState(gameMenu);
wont work.
Instead i need to create new substate directly
openSubState(new MySubstate());

Dialog values with MvvmCross, ActionBarSherlock and DialogFragment

I have a bunch of different libraries trying to work together and I'm pretty close but there's just one issue.
I have created a class called SherlockDialogFragment inheriting from SherlockFragment (rather than using the SherlockListFragment - this is because of the issue with the keyboard that's covered here). Here is my code:
public class SherlockDialogFragment : SherlockFragment
{
public RootElement Root
{
get { return View.FindViewById<LinearDialogScrollView>(Android.Resource.Id.List).Root; }
set { View.FindViewById<LinearDialogScrollView>(Android.Resource.Id.List).Root = value; }
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignored = base.OnCreateView(inflater, container, savedInstanceState);
var layout = new LinearLayout(Activity) { Orientation = Orientation.Vertical };
var scroll_view = new LinearDialogScrollView(Activity)
{
Id = Android.Resource.Id.List,
LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FillParent, ViewGroup.LayoutParams.FillParent)
};
layout.AddView(scroll_view);
return layout;
}
}
I then do the regular thing of creating an eventsource class which inherits from this but also uses IMvxEventSourceFragment, then the actual fragment class (which I call MvxSherlockDialogFragment) which inherits the eventsource class, as well as IMvxFragmentView.
That all works fine (and indeed I've created a SherlockDialogActivity the same way and it's fine), however the one issue is when I use this fragment on a screen with tabs (i'm using a class I made similarly to above called MvxSherlockFragmentActivity). When switching to the tab with the dialog, the view appears fine, even with pre-populated data. However the issue is when I switch away from that fragment/tab, and then back to it, the dialog elements all have the same value.
In my particular example, it's a login page with a username and password. When I first go into the fragment, everything is fine. When I go out and back in, the password value is in both the username field and the password field.
I'm sure it's got something to do with the SherlockDialogFragment class - in the SherlockDialogActivity class I also have this bit:
public override void OnContentChanged()
{
base.OnContentChanged();
var list = FindViewById<LinearDialogScrollView>(Android.Resource.Id.List);
if (list == null)
{
throw new RuntimeException("Your content must have a ViewGroup whose id attribute is Android.Resource.Id.List and is of type LinearDialogScrollView");
}
list.AddViews();
}
However this doesn't work in a fragment because there's no OnContentChanged event. Also, another difference is that in the SherlockDialogActivity, the layout is being created ONCE in the OnCreate event - however in the SherlockFragmentActivity I've got it being created each time the fragment is viewed. I know that's probably not the best way, but I tried to do it in OnCreate and save it in a variable and then return that variable in OnCreateView, but android didn't like that...
Ok I feel like an idiot. I was creating/binding on OnViewCreated - however I need to do all my binding in OnStart - I think I was following some (possibly old) sample code from Stuart.
Obviously for a regular activity I'm using OnCreate but this doesn't work on a fragment, because the view is not initialised there - it's initialised at OnCreateView.
So for future reference - do all binding in OnStart!

Having trouble with AsyncTask using a recursive method

I've been reading about AsyncTasks and Hanlders and Loopers but I still can't figure out where I'm going wrong in my code. I'm trying to run code that will look over a Tic Tac Toe grid and determine the best move for the computer. I want this code to run in the background 'cause it can take some time and then I can update the UI level with a textbox that says something like "I'm Thinking". I've tried this a bunch of different ways, none with success.
private class PostTask extends AsyncTask<String, Integer, String> {
private Board _b;
private Welcome.Player _opp;
private int _depth;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected void SetVars(Board b, Player p, int depth){
_b = b;
_opp = p;
_depth = depth;
}
#Override
protected String doInBackground(String... params) {
Looper.prepare();
try{
_bestMove = _b.GetBestMove(_opp,_depth);
}
catch(Exception err){
_bestMove = -1;
}
return "All done";
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(_bestMove == -1){
TextView tv = (TextView) findViewById(R.id.tv_Score);
tv.setText("Had and error, couldn't make a move.");
}
FollowUpComputerMove(this);
}
The above code will work for exactly 5 moves and then it crashes. When I watch in the debugger I see new theads being created named Thread<#> AsyncTask #1. Once I get to five of those AsyncTasks it goes back to try and grab the first AsyncTask and crashes. When it crashes I'm shown the ThreadPoolExecutor.class file.
I've also read that I shouldn't be using both the AsyncTask and the Looper objects together so I've tried taking the Loooper.prepare() statement out, but then my AsyncTask fails immediately with the error message:
Can't create handler inside thread that has not called Looper.prepare() - AsyncTask inside a dialog
I've read repeatedly that you shouldn't be trying to update the UI from an AsyncTask and that often the above error is because of that, but GetBestMove isn't updating the UI thread. When I trace through to see where the error comes, it fails when calling a constructor saying it can't find the class.
Can anyone point me in the right direction? My end goal is to use one main thread and only one background thread, and just keep re-using the background thread whenever the computer needs to make a move. I know that the recursive method GetBestMove works when I run this program in a single-thread manner. But the screen freezes for too long on some moves as the method is being run. Thank you so much.
-NifflerX
Apologies for answering my own question, but the issue I was facing had nothing to do with recursion. The class I was calling was extending the class Activity, and while trying to call that from an AsyncTask the program was erroring out. When I removed the extends Activity from the class definition it started working again. Sorry for the post.
-NifflerX

Form won't display. . . Dooh!

I could use a little help. I got this program to work right then I found out I had to use the MVC design. It seems pretty simple but, my little toy program won't display my forms. HELP!! See the below snipets:
PART OF MIDLET
public MileageMidlet()
{
// First get a blank user form
form = new Form("Bradford Gas Mileage Calculator");
startPage = new StartPageView();
inputScreen = new InputScreen();
calculateMileage = new CalculateMileage();
startCmd = new Command ("Start",Command.SCREEN,5);
clearCmd = new Command ("Clear",Command.SCREEN,1);
enterCmd = new Command ("Enter",Command.SCREEN,1);
exitCmd = new Command("Exit", Command.EXIT, 1);
// Set up event handlers to process user commands
form.setCommandListener(this);
}
public void startApp() {
startPage.createView(form);
form.addCommand(startCmd);
form.addCommand(exitCmd);
// Display initial form
Display.getDisplay(this).setCurrent(form);
}
START PAGE VIEW CLASS
import javax.microedition.lcdui.*;
public class StartPageView
{
StringItem strgItm, strgItm2;
private Command startCmd, exitCmd;
public StartPageView()
{
}
public void createView(Form form)
{
// First get a blank user form
form.deleteAll();
form = new Form("Bradford Gas Mileage Calculator");
strgItm = new StringItem ("","Welcome to the Bradford Mobile Gas Mileage Calculator!");
strgItm2 = new StringItem ("","To obtain you gas mileage please click the start button.");
form.append(strgItm);
form.append(strgItm2);
}
I got nothing! Really literally a blue screen.
}
The issue has nothing to do with MIDP or J2ME. The problem is of the semantics of how arguments are passed to methods.
It;s important to remember that arguments to method are passed by value in Java. The consequence is that when an object that is passed to a method, a copy of that reference is passed. Any changes to the reference of the object in the method does not have any affect outside of it.
Please see this article for more information.
So in your code,
form.deleteAll();
form = new Form("Bradford Gas Mileage Calculator");
Comment the above two lines. Everything should be fine.

Resources