I'm building a UI for a Simulator running in background. Since this Simulator may not hold for a long time, it of course has to be in a separate thread from the JavaFx Thread. I want to start, pause, resume and stop/terminate the Simulator when the corresponding button is clicked.
The service class that advances the simulator looks like this:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class SimulatorService extends Service<Void> {
private Simulator simulator;
private long cycleLengthMS = 1000;
private final AtomicBoolean simulatorStopped = new AtomicBoolean(false);
public SimulatorService(Simulator simulator){
this.simulator = simulator;
}
#Override
protected Task<Void> createTask() {
return new Task<>() {
#Override
protected Void call() {
System.out.println("Requested start of Simulator");
int state;
do {
// advance
state = simulator.nextStep();
try {
TimeUnit.MILLISECONDS.sleep(cycleLengthMS);
if(simulatorStopped.get()){
super.cancel();
}
} catch (InterruptedException e) {
return null;
}
}
while (state == 0 && !simulatorStopped.get());
return null;
}
};
}
#Override
public void start(){
if(getState().equals(State.READY)){
simulatorStopped.set(false);
super.start();
}
else if(getState().equals(State.CANCELLED)){
simulatorStopped.set(false);
super.restart();
}
}
#Override
public boolean cancel(){
if(simulatorStopped.get()){
simulatorStopped.set(true);
return false;
} else{
simulatorStopped.set(true);
return true; //if value changed
}
}
}
The Simulator starts the Service if a button on the GUI is pressed:
import javafx.application.Platform;
import java.util.concurrent.atomic.AtomicInteger;
public class Simulator {
Model model;
private final SimulatorService simulatorService;
public Simulator(Model model){
this.model = model;
simulatorService = new SimulatorService(this);
}
public int nextStep(){
final AtomicInteger res = new AtomicInteger(0);
Platform.runLater(new Thread(()-> {
res.set(model.nextStep());
}));
return res.get();
}
public boolean stopSimulationService() throws IllegalStateException{
return simulatorService.cancel();
}
public void startSimulationService() throws IllegalStateException{
simulatorService.start();
}
}
Parts of the window are redrawn if a observed value in the model changes:
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public class Model {
private final IntegerProperty observedValue = new SimpleIntegerProperty(0);
public int nextStep() {
observedValue.set(observedValue.get() + 1);
return observedValue.get() > 500000 ? 1 : 0;
}
public int getObservedValue() {
return observedValue.get();
}
public IntegerProperty observedValueProperty() {
return observedValue;
}
public void setObservedValue(int observedValue) {
this.observedValue.set(observedValue);
}
}
The redraw happens in another class:
import javafx.beans.value.ChangeListener;
public class ViewController {
private View view;
private Simulator simulator;
private Model model;
public ViewController(Simulator simulator) {
this.simulator = simulator;
this.view = new View();
setModel(simulator.model);
view.nextStep.setOnMouseClicked(click -> {
simulator.nextStep();
});
view.startSim.setOnMouseClicked(click -> {
simulator.startSimulationService();
});
view.stopSim.setOnMouseClicked(click ->{
simulator.stopSimulationService();
});
}
public View getView() {
return view;
}
private final ChangeListener<Number> observedValueListener = (observableValue, oldInt, newInt) -> {
view.updateView(newInt.intValue());
};
public void setModel(Model m) {
this.model = m;
m.observedValueProperty().addListener(observedValueListener);
}
}
The corresponding view:
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
public class View extends BorderPane {
Button nextStep = new Button("next step");
Button startSim = new Button("start");
Button stopSim = new Button("stop");
GridPane buttons = new GridPane();
Text num = new Text();
public View(){
buttons.add(nextStep,0,0);
buttons.add(startSim,0,1);
buttons.add(stopSim,0,2);
buttons.setAlignment(Pos.BOTTOM_LEFT);
setCenter(buttons);
setTop(num);
}
public void updateView(int num){
this.num.setText("" + num);
}
}
Main:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
ViewController c = new ViewController(new Simulator(new Model()));
Scene scene = new Scene(c.getView(),200,200);
stage.setScene(scene);
stage.show();
}
}
I am trying to update markers on Google map using a service, but when I use the "setParkingSpotMarker" function that add a marker to every item at the list I get an error "java.lang.IllegalStateException: Not on the main thread"
The function "setParkingSpotMarker" is called in the loop inside the service -DataUpdateService.
I don't know how to change my code so it will update the markers on the main thread.I have read some posts about that but didn't understand how to change it in my code.
this is the service:
package com.example.sailon;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class DataUpdateService extends Service {
Timer myTimer = new Timer();
MyTimerTask myTask = new MyTimerTask();
MyMap mymap;
String teamID;
static LatLng teamLocation;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
String action;
Context fromContext;
String CompName;
String heatNum;
boolean isSailor;
String usermail;
GPSTracker gps;
private final IBinder mBinder = new LocalBinder();
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PS", "DataUpdateService onStartCommand");
return Service.START_NOT_STICKY;
}
#Override
// return thee instance of the local binder to the activity
public IBinder onBind(Intent intent) {
Log.d("PS", "DataUpdateService onBind");
return mBinder;
}
public class LocalBinder extends Binder {
DataUpdateService getService() {
Log.d("PS", "DataUpdateService LocalBinder onBind");
return DataUpdateService.this;
}
}
public class MyTimerTask extends TimerTask {
#Override
public void run() {
String unitToUpdate= mymap.getUnitToUpdate (CompName,heatNum,usermail);
Log.d("NY","CompName " +CompName);
Log.d("NY","heatNum " +heatNum);
Log.d("NY","usermail " +usermail);
Log.d("NY","unitToUpdate" +unitToUpdate);
Log.d("NY","isSailor" +isSailor);
if (isSailor){
gps = new GPSTracker(DataUpdateService.this,unitToUpdate );
if( ! (gps.canGetLocation())){
gps.showSettingsAlert();
}
}
unitswithteam=mymap.refresh (CompName,heatNum);
int j= unitswithteam.size();
for (int i=0; i<j;i++){
teamID=unitswithteam.get(i).getTeamID();
Log.d("NY","teamID "+i+teamID);
UnitsInHeats us=unitswithteam.get(i).getUnit();
teamLocation = new LatLng(us.getLat(),us.getLng() );
Log.d("NY","team location "+i + " "+us.getLat());
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
}
}
}
// called from the activity
public void MapUpdateFromService(Context context, MyMap map, final String action,
String CompName, String heatNum, boolean isSailor , String usermail) {
Log.d("PS", "DataUpdateService MapUpdateFromService");
this.mymap = map;
this.action = action;
this.CompName=CompName;
this.heatNum=heatNum;
this.isSailor=isSailor;
this.usermail=usermail;
// this command activate the run function from the inner class MyTimerTask every 5 seconds.
myTimer.schedule(myTask,0,5000);
}
public void onDestroy() {
super.onDestroy();
// cancel the scheduler.
myTimer.cancel();
}
}
this is the activity that calls the service:
package com.example.sailon;
import java.util.ArrayList;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class Map extends Activity {
Bundle extras;
// private GoogleMap map;
static LatLng teamLocation;
//public static ArrayList<Teams> teams;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
Marker mark;
double lat;
double lng;
GPSTracker gps;
String Location ;
String teamID;
String CompName;
MyMap mymap;
String heatNum;
String CompID;
boolean isSailor;
String usermail;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
public ArrayList<UnitInHeatForMap> unitswithteam= new ArrayList<UnitInHeatForMap>();
// ArrayList<LatLng> List= new ArrayList<LatLng>() ;
DataUpdateService dbuService;
boolean dbuBound=false;// when service connected get true
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
mymap= new MyMap(this,((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap());
//map=((MapFragment)getFragmentManager().findFragmentById(R.id.map)).getMap();
extras = getIntent().getExtras();
CompName=extras.getString("CompName");
heatNum=extras.getString("heatNum");
isSailor=extras.getBoolean("isSailor");
usermail=extras.getString("usermail");
Log.d("CompName",CompName);
Log.d("heatNum",heatNum);
// get action bar
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
if (mymap!=null){
Log.d("PS", "map isnt null");
mymap.setMapType();
mymap.setMyLocationEnabled(true);
CameraPosition firstZom =new CameraPosition.Builder()
.target(BeerSheva)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(firstZom);
}
}
// serviceConnerction is an interface that must be implemented when using bound service
private ServiceConnection sConnection=new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.d("PS", "Map onServiceConnected");
DataUpdateService.LocalBinder binder=(DataUpdateService.LocalBinder)service;
dbuService=binder.getService();
Log.d("PS", "Map callupdate");
dbuService.MapUpdateFromService(Map.this,mymap,"ActionSearch",CompName,heatNum, isSailor,usermail);
dbuBound=true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.d("PS", "Map onServiceDisconnected");
dbuBound=false;
}
};
#Override
protected void onStart() {
super.onStart();
// Bind to DataUpdateService
Log.d("PS", "Map onStart");
Intent intent= new Intent(this,DataUpdateService.class);
bindService(intent,sConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStop() {
super.onStop();
// Unbind from the service
Log.d("PS", "Map onStop");
if(dbuBound){
unbindService(sConnection);
dbuBound=false;
}
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.logoutAction:
Intent i = new Intent(Map.this, MainActivity.class);
startActivity(i);
return true;
case R.id.VideoAction:
Intent intent = new Intent("android.media.action.VIDEO_CAMERA");
startActivity(intent);
return true;
case R.id.CallAction:
Intent call = new Intent(Intent.ACTION_DIAL);
startActivity(call);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
this is the calss of the map:
package com.example.sailon;
import android.content.Context;
import android.util.Log;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.parse.ParseException;
import java.util.ArrayList;
/**
* Created by Evyatar.m on 21/02/2015.
*/
public class MyMap {
private GoogleMap map;
static LatLng BeerSheva = new LatLng(31.250919, 34.783916);
String CompID;
String teamID;
String CompName;
String heatNum;
ArrayList<TeamsList> teamsList= new ArrayList<TeamsList>() ;
public ArrayList<UnitInHeatForMap> unitswithteam2= new ArrayList<UnitInHeatForMap>();
static LatLng teamLocation;
Model DB;
public MyMap(Context context, GoogleMap map) {
Log.d("PS", "MyMap builder");
DB = Model.getInstance(context);
this.map = map;
}
public String getUnitToUpdate (String CompName,String heatNum, String usermail){
String unit=null;
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
unit= DB.getUnitToUpdateFromDB (CompID,heatNum, usermail);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unit;
}
public void setMyLocationEnabled(boolean b){
Log.d("PS", "MyMap set location enable");
map.setMyLocationEnabled(true);
}
public void setParkingSpotMarker(LatLng teamLocation,String teamID) {
Log.d("PS", "ParkingMap setParkinSpotMarker");
map.addMarker(new MarkerOptions()
.position(teamLocation)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.iconsmall))
.title("Team " +teamID)).showInfoWindow();
}
public void setMapType(){
Log.d("PS", "MyMap setType");
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
public void moveMyMapCamera(CameraPosition firstZom) {
Log.d("PS", "MyMap moveParkingMapCamera");
map.moveCamera(CameraUpdateFactory.newCameraPosition(firstZom));
}
//updates all points on map
public ArrayList<UnitInHeatForMap> refresh (String CompName,String heatNum){
Log.d("PS", "MyMap refresh");
try {
CompID= DB.getCompIDByName(CompName);
} catch (com.parse.ParseException e) {
e.printStackTrace();
}
try {
DB.setUnitInHeatForMap (new Model.CallbackModel () {
#Override
public void done (ArrayList<UnitInHeatForMap> unitswithteam){
if (unitswithteam.size() >0){
unitswithteam2=unitswithteam;
}
}
}, CompID, heatNum,this);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return unitswithteam2;
}
}
please help me
thanks !!!**
The run method of the TimerTask runs on background thread, and you can only update the map on the main thread.
So you have to wrap the following Map UI update codes into runOnUiThread()
mymap.setParkingSpotMarker(teamLocation,teamID);
if (i==(j-1)){
CameraPosition secound =new CameraPosition.Builder()
.target(teamLocation)
.zoom(15.5f)
.bearing(300)
.tilt(50)
.build();
mymap.moveMyMapCamera(secound);
}
You need to have an Activity to apply runOnUIThread, so you need to put your
fromContext = ((Map)context);
inside the first line of your MapUpdateFromService method. Then you can call runOnUiThread() in your TimerTask's run() method.
((Map)fromContext).runOnUiThread(new Runnable() {
#Override
public void run() {
//run your Map UI update code
}
});
This is also a similar issue of this problem.
Is it possible to get the value of phobe in-call volume from java me midlet? Changing of the volume is not necessary.
Thanks.
AFAIK,
It is not possible to access the phone volume. But you can set your application volume or get the application.
Sample code for Controlling the volume of your application :
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.Ticker;
import javax.microedition.media.*;
public class VolumeControlDemo extends MIDlet implements CommandListener {
private Display display;
private Command exit,incr,decr;
Form frm;
VolumeControl vc;
int vol;
Player player;
public VolumeControlDemo() {
display = Display.getDisplay(this);
}
public void startApp() {
frm=new Form("VolumeControlDemo Demo");
exit= new Command("Exit",Command.EXIT,1);
decr= new Command("Decrease",Command.EXIT,1);
incr= new Command("Increase",Command.EXIT,1);
frm.addCommand(exit);
frm.addCommand(decr);
frm.addCommand(incr);
frm.setCommandListener(this);
display.setCurrent(frm);
try {
// Creating player object
player = Manager.createPlayer("/demo.wav");
// Setting loop count
player.setLoopCount(-1);
// Start sound
player.start();
Control cs[];
// Getting Controls object
cs = player.getControls();
for (int i = 0; i < cs.length; i++) {
if (cs[i] instanceof VolumeControl)
// Getting volume control
vc=(VolumeControl)cs[i];
}
} catch (Exception e) {}
}
public void pauseApp() {
}
public void destroyApp(boolean un) {
}
public void commandAction(Command cmd,Displayable d) {
try {
if(decr) {
if(vol>0) vol--;
vc.setLevel(vol);
} else if() {
if(vol<99) vol--;
vc.setLevel(vol);
}
frm.appent("vol="+vc.getLevel());
}catch(Exception e){}
}
}
I want to develop a client app for website .
I want the app to reside in system tray when minimised.
I dont know how to accomplish this task .
Is their any example for this type of operation.
The key here is to set the implicit exit to false Platform.setImplicitExit(false);
Also is important to show and hide the stage in a new thread.
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.hide();
}
});
Next, the whole code:
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.imageio.ImageIO;
/**
*
* #author alvaro
*/
public class TrayTest extends Application {
private boolean firstTime;
private TrayIcon trayIcon;
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
createTrayIcon(stage);
firstTime = true;
Platform.setImplicitExit(false);
Scene scene = new Scene(new Group(), 800, 600);
stage.setScene(scene);
stage.show();
}
public void createTrayIcon(final Stage stage) {
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
java.awt.Image image = null;
try {
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
image = ImageIO.read(url);
} catch (IOException ex) {
System.out.println(ex);
}
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
hide(stage);
}
});
// create a action listener to listen for default action executed on the tray icon
final ActionListener closeListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
System.exit(0);
}
};
ActionListener showListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(showListener);
popup.add(showItem);
MenuItem closeItem = new MenuItem("Close");
closeItem.addActionListener(closeListener);
popup.add(closeItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Title", popup);
// set the TrayIcon properties
trayIcon.addActionListener(showListener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
}
}
public void showProgramIsMinimizedMsg() {
if (firstTime) {
trayIcon.displayMessage("Some message.",
"Some other message.",
TrayIcon.MessageType.INFO);
firstTime = false;
}
}
private void hide(final Stage stage) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (SystemTray.isSupported()) {
stage.hide();
showProgramIsMinimizedMsg();
} else {
System.exit(0);
}
}
});
}
}
As far as I know it will be possible in JFX 8. Right now the best solution is to embed your application into AWT and hide the AWT window itself.
I have a TextField in a form:
private TextField cc1F = new TextField("", "", 250, TextField.ANY);
Once click button OK, then set cc1F field's Constraints to:
cc1F.setConstraints(TextField.UNEDITABLE);
then I am getting an exception:
java.lang.NullPointerException
at com.sun.midp.lcdui.DefaultInputMethodHandler.setConstraints(+63)
at javax.microedition.lcdui.TextField$InputMethodClientImpl.setConstraints(+20)
at javax.microedition.lcdui.TextField.setConstraints(+37)
at com.zousys.j2me.zmail.gui.view.HeaderView.menuAction(+146)
.....................................
Anyone know this?
The example of code was tested with simulator WTK 3.0 and device Samsung Chat
http://www.gsmarena.com/samsung_ch#t_527-4096.php and the test passed. :)
I think that the problem is caused by device model or the object cc1F is null.
import java.io.UnsupportedEncodingException;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TextFieldMIDlet extends MIDlet implements CommandListener {
private Form form;
private Command cmdExit;
private Command cmdSetConstraints;
private Display display;
private TextField textField;
public TextFieldMIDlet() {
form = new Form("Testing constraints");
cmdExit = new Command("Exit",Command.EXIT, 1);
cmdSetConstraints = new Command("Set Constraints",Command.ITEM, 1);
textField = new TextField("", "", 250, TextField.ANY);
form.addCommand(cmdExit);
form.addCommand(cmdSetConstraints);
form.append(textField);
display = Display.getDisplay(this);
form.setCommandListener(this);
}
protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub
}
protected void pauseApp() {
// TODO Auto-generated method stub
}
protected void startApp() throws MIDletStateChangeException {
display.setCurrent(form);
}
public void commandAction(Command c, Displayable d) {
if (c == cmdExit) {
this.notifyDestroyed();
} else if (c == cmdSetConstraints) {
try {
System.out.println("Set...");
if (textField.getConstraints() == TextField.UNEDITABLE) {
textField.setConstraints(TextField.ANY );
} else {
textField.setConstraints(TextField.UNEDITABLE );
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}