How autocall method in JavaFX? - javafx-2

I have scene with label which shows what part of hardware are being checked at the moment, so i need invoke "checkMethod" automatically after scene has been drawn, how can i do it in JavaFX?

Here is how to do something when the Scene is shown:
stage.setOnShown(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent arg0) {
// TODO Auto-generated method stub
checkMethod();
}
});
You also have this other methods: setOnCloseRequest, setOnHidden, setOnHiding, setOnShowing.
The option proposed in comments Its the followin:
scene.windowProperty().addListener(new ChangeListener<Window>() {
#Override
public void changed(ObservableValue<? extends Window> arg0,
Window oldVal, Window newVal) {
if(oldVal != null){
oldVal.setOnShown(null);
}
if(newVal != null){
newVal.setOnShown(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent arg0) {
// TODO Auto-generated method stub
checkMethod();
}
});
}
}
});

Related

I want to change my WebView content from a HTML file using thread in javafx

Here is my code. I am using scene builder. The code is not working.For first time it loads the hello1.html but in thread the hello2.html does not load.
public class TwavlController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML public WebView webPane;
private Service<Void> back_thread;
private WebEngine engine;
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
engine = webPane.getEngine();
final String html_file = "hello1.html"; //HTML file to view in web view
URL urlHello = getClass().getResource(html_file);
engine.load(urlHello.toExternalForm());
run();
}
private File last_update,current;
public void run(){
back_thread = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
updateMessage("hello2.html");
return null;
}
};
}
};
engine.userAgentProperty().bind(back_thread.messageProperty());
back_thread.restart();
}
}
I'm not really clear what you're trying to do here, but I think maybe you are looking for
public void run(){
back_thread = new Service<Void>() {
#Override
protected Task<Void> createTask() {
return new Task<Void>() {
#Override
protected Void call() throws Exception {
Platform.runLater(() ->
engine.load(getClass().getResource("hello2.html").toExternalForm()));
return null;
}
};
}
};
back_thread.restart();
}

How to open dialog box in android as soon as game ends from surfaceview class

I have made a SurfaceView subclass in MainActivity which runs some animation/game/thread via canvas draw and I want a dialog box to appear as soon as game ends. I have made a function called openNewGameDialog where I call new AlertDialog.Builder(MainActivity.this) however since I am calling this from a thread it gives error. Please help!! Following is the code:
public class MainActivity extends Activity implements OnTouchListener{
GameSurface dSurface;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dSurface=new GameSurface(this);
dSurface.setOnTouchListener(this);
initialize();
setContentView(dSurface);
}
private void initialize(){
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
dSurface.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
dSurface.resume();
}
private void openNewGameDialog(){
new AlertDialog.Builder(MainActivity.this)
.setTitle("hhhhhh")
.setItems(R.array.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.show();
}
public class GameSurface extends SurfaceView implements Runnable{
SurfaceHolder gameHolder;
Thread gameThread = null;
public GameSurface(Context context) {
super(context);
// TODO Auto-generated constructor stub
gameHolder = getHolder();
}
public void pause(){
isRunning = false;
while(true)
{
try {
gameThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
gameThread=null;
}
public void resume(){
isRunning = true;
gameThread = new Thread(this);
gameThread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
if(!gameHolder.getSurface().isValid())
continue;
Canvas canvas = gameHolder.lockCanvas();
canvas.draw something
if game==ends
openNewGameDialog();
gameHolder.unlockCanvasAndPost(canvas);
}
}
}
}
You must put the contents of openNewGameDialog() in a Runnable instead of a method and then call the runOnUiThread(Runnable r) method of the Activity class using that Runnable.
Any kind of UI manipulation can only be done by the UI thread. TherunOnUiThread(Runnable r) method queues the Runnable to the UI thread event queue.

How to make checkbox or combobox readonly in JavaFX

How to make checkbox/combobox readonly in javaFX but not disabled.
I tried consuming onAction event but it didn't work.
checkBox.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
event.consume();
}
});
Consuming all events like in code below works but I don't think it's a good solution:
checkBox.addEventFilter(KeyEvent.ANY, new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
event.consume();
}
});
checkBox.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEventevent) {
event.consume();
}
});
You can set the check box to disabled but set the the look of it using CSS. If you are using the default style you can make the check box look 'normal' by setting full opacity.
checkbox.setStyle("-fx-opacity: 1");
It is probably a similar deal with the combo box.
You can override method CheckBox#arm() with an empty one:
CheckBox cb = new CheckBox("hi") {
#Override
public void arm() {
// intentionally do nothing
}
};
If you do not want to overwrite the CheckBok class, you can use the selectedProperty.
CheckBox cb = new CheckBox("hi");
cb.selectedProperty().addListener(new NCL());
class NCL implements ChangeListener<Boolean> {
#Override
public void changed(ObservableValue<? extends Boolean> ov, Boolean old_val, Boolean new_val) {
cb.setSelected(false);
}
}

mapview and cameraupdate in api v2

Why the CameraUpdateFactory class is not working in my project?
The app crashes if it executes the following command:
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
If i remove that line (and of course the next one), the code successfully starts and shows the map.
I need the mapView and i need to use the new api v2.
I declare the mapView in layout in this way:
<com.google.android.gms.maps.MapView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/mappa"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/buttonBar"
map:uiZoomControls="false"
/>
then in mainActivity.java i wrote this:
public class MainActivity extends FragmentActivity implements LocationListener, LocationSource {
public static boolean locatingMe=true;
public GoogleMap mappa;
public MapView mapView;
private OnLocationChangedListener onLocationChangedListener;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mappa);
mapView.onCreate(savedInstanceState);
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
//You may want to pass a different provider in as the first arg here
//depending on the location accuracy that you desire
//see LocationManager.getBestProvider()
Criteria locationCriteria = new Criteria();
locationCriteria.setAccuracy(Criteria.NO_REQUIREMENT);
locationManager.requestLocationUpdates(locationManager.getBestProvider(locationCriteria, true), 1L, 2F, this);
if (mappa == null) {
mappa=mapView.getMap();
//This is how you register the LocationSource
mappa.setLocationSource(this);
mappa.getUiSettings().setMyLocationButtonEnabled(false);
mappa.setMyLocationEnabled(true);
}
}
#Override
public void onPause()
{
if(locationManager != null)
{
locationManager.removeUpdates(this);
}
mapView.onPause();
super.onPause();
}
#Override
public void onResume()
{
checkGooglePlayServicesAvailability();
checkGps();
mapView.onResume();
super.onResume();
}
#Override
protected void onDestroy() {
mapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
public void activate(OnLocationChangedListener listener)
{
onLocationChangedListener = listener;
}
#Override
public void deactivate()
{
onLocationChangedListener = null;
}
#Override
public void onLocationChanged(Location location)
{
if( onLocationChangedListener != null )
{
onLocationChangedListener.onLocationChanged( location );
//Move the camera to the user's location once it's available!
//only if locatingMe is true
if (locatingMe) {
if (mappa!=null){
CameraUpdate pino= CameraUpdateFactory.newLatLng(new LatLng(location.getLatitude(), location.getLongitude()));
mappa.animateCamera(pino);
}
}
}
}
#Override
public void onProviderDisabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider)
{
// TODO Auto-generated method stub
Toast.makeText(this, "provider enabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// TODO Auto-generated method stub
Toast.makeText(this, "status changed", Toast.LENGTH_SHORT).show();
}
The error in the LogCat is the following:
Caused by: java.lang.NullPointerException: CameraUpdateFactory is not initialized.
I solved the problem by adding on the "onCreate" the following lines:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
the reason is that the CameraUpdateFactory needs to be initilized (even if from documentation it seems that using mapview it shoud be automatically initialized)
I even replaced "public class MainActivity extends FragmentActivity" with "public class MainActivity extends Activity". But i think that this last thing it was not needed..
if i use:
try {
MapsInitializer.initialize(this);
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
The exception give me this error:
Unreachable catch block for GooglePlayServicesNotAvailableException.
This exception is never thrown from the try statement body".
I have use only:
MapsInitializer.initialize(this);
:)

Detecting the Secondary mouse button in the text area and table view using javafx

private void gotoRightClick() {
textArea.setOnMouseClicked(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent event) {
if(event.isSecondaryButtonDown())
{
System.out.println("right click pressed in text area");
}
}
});
tableView.setOnMouseClicked(new EventHandler<MouseEvent>(){
#Override
public void handle(MouseEvent e) {
if(e.isSecondaryButtonDown())
{
System.out.println("right click pressed in table view");
}
}
});
}
None of the event is detecting can any one help me?
Thanks Advance
Try this:
this.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (event.getButton().equals(MouseButton.SECONDARY)) {
//do something
}
}
});

Resources