Map fragment doesn't move to current location when Recreated - google-maps

Greetings to the community. This is my first question, please guide me if I did any mistake.
I have four fragments in my app. An activity(Main Activity) that hosts all the four fragments.
Google Maps Fragment
Fragment two
Fragment three
Fragment four
When the application starts. Maps fragment is loaded and it shows marker at my current location. But when I move from Maps fragment to Fragment two and then came back to Map Fragment it doesn't show my current location
Here is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
// Fragments
private MapsFragment mapsFragment = new MapsFragment();
private QrScanFragment qrScanFragment = new QrScanFragment();
private SeatsFullFragment seatsFullFragment = new SeatsFullFragment();
private EmergencyFragment emergencyFragment = new EmergencyFragment();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initLayouts();
initListeners();
// Maps Fragment Loaded
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
loadFragment(mapsFragment);
}
}
loadFragment(Fragment fragment)
public void loadFragment(Fragment fragment) {
if (fragment != null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, fragment)
.commit();
}
}
Moving b/w fragments
if (view == mLlMaps) {
if (!mapsFragment.isVisible()) {
loadFragment(mapsFragment);
mTvTitle.setText("Map");
}
mIvMaps.setImageResource(R.drawable.ic_map_pin_2_line_fill);
mIvMaps.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
} else if (view == mLlQrScan) {
if (!qrScanFragment.isVisible()) {
loadFragment(qrScanFragment);
mTvTitle.setText("ScanQR");
}
mIvQrScan.setImageResource(R.drawable.ic_baseline_qr_code_scanner_24_fill);
mIvQrScan.setBackground(getResources().getDrawable(R.drawable.bg_tint_icon));
}
}
MapsFragment.java
public class MapsFragment extends Fragment implements OnMapReadyCallback {
private GoogleMap mMap;
private SupportMapFragment mapFragment;
// To get Current Location of Driver
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
public MapsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_maps, container, false);
buildLocationRequest(); // Request for current Location
buildLocationCallback(); // When location is provided
updateLocation(); // Fused Location Provider
// Child Fragment Manager copied from Uber
mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
return view;
}
// Request for current Location
private void buildLocationRequest() {
if (locationRequest == null) {
locationRequest = new LocationRequest();
locationRequest.setSmallestDisplacement(50f); // 50m
locationRequest.setInterval(15000); // 15s
locationRequest.setFastestInterval(10000); // 10s
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
// When location result is provided
private void buildLocationCallback() {
if (locationCallback == null) {
locationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
LatLng newPosition = new LatLng(locationResult.getLastLocation().getLatitude(),
locationResult.getLastLocation().getLongitude());
// 18f is the radius of circle
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(newPosition, 18f));
}
};
}
}
// Fused Location Provider
private void updateLocation() {
if (fusedLocationProviderClient == null) {
fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(getContext());
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getActivity(), "Permission Required", Toast.LENGTH_SHORT).show();
return;
}
fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.myLooper());
}
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
Log.d("EB", "onMapReady: called");
// Check Permission
Dexter.withContext(getContext())
.withPermission(Manifest.permission.ACCESS_FINE_LOCATION)
.withListener(new PermissionListener() {
#Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse) {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setMyLocationButtonEnabled(true);
mMap.setOnMyLocationButtonClickListener(new GoogleMap.OnMyLocationButtonClickListener() {
#Override
public boolean onMyLocationButtonClick() {
if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
Toast.makeText(getContext(), "Permission Granted", Toast.LENGTH_SHORT).show();
}
fusedLocationProviderClient.getLastLocation().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
LatLng userLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
// 18f is the radius of circle
mMap.animateCamera(CameraUpdateFactory
.newLatLngZoom(userLatLng, 18f));
}
});
return true;
}
});
// Set Layout - Location Button
View locationButton = ((View) mapFragment.getView().findViewById(Integer.parseInt("1"))
.getParent())
.findViewById(Integer.parseInt("2"));
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
locationButton.getLayoutParams();
//Right Bottom
params.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.setMargins(0, 0, 0, 50);
// Move to current Location
buildLocationRequest();
buildLocationCallback();
updateLocation();
}
#Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse) {
Toast.makeText(getContext(),
"Permission" + permissionDeniedResponse.getPermissionName() + "wasdenied",
Toast.LENGTH_SHORT).show();
}
#Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken) {
}
}).check();
// Change/Parse the Maps Style
try {
boolean success = googleMap.setMapStyle(MapStyleOptions
.loadRawResourceStyle(getContext(), R.raw.uber_maps_style));
if (!success)
Log.e("Error", "Style parsing Error");
} catch (Resources.NotFoundException e) {
Log.e("Error", e.getMessage());
}
}
}

Related

I am not able to zoom camera in by animating google camera when i am using custom popup on click of marker

In on mapReady function of google map i have written
below: it basically forms cluster of marker location data and pass it
to the cluster manager
How can i do googleMap.animateCamera() on getInfoWindow() as it not working to get zoomed in by animating camera on click of marker
with popup opened.
mClusterManager = new ClusterManager<>(getActivity(), mMap);
mClusterManager.setAlgorithm(getAlgorithm());
mClusterManager.setRenderer(new MyRenderer(getActivity(), mMap));
mClusterManager.setAnimation(true);
//To set custom dialog on marker click
mClusterManager.getMarkerCollection().setInfoWindowAdapter(new PubLocationCustomClusterInfoView(this, getActivity(), pubArrayList, this, getMap()));
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<PubLocation>() {
#Override
public boolean onClusterItemClick(PubLocation item) {
return false;
}
});
PubLocationCustomClusterInfoView.java -- This is my custom view for
marker popup where i want to zoom in by animating google camera but im
unable to.
public class PubLocationCustomClusterInfoView implements GoogleMap.InfoWindowAdapter {
private View clusterItemView;
private static final String TAG = "PubLocationCustomCluste";
Context context;
private OnInfoWindowElemTouchListener infoButtonListener,orderFromPubListener;
ArrayList<PubData.Pub> pubArrayList;
MarkerInfoWindow markerInfoWindowlistner;
MapMarkerOnClickListener mapMarkerOnClickListener;
GoogleMap googleMap;
public PubLocationCustomClusterInfoView(MarkerInfoWindow markerInfoWindow, Context context, ArrayList<PubData.Pub> pubArrayList, MapMarkerOnClickListener mapMarkerOnClickListener,GoogleMap googleMap) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
this.context=context;
this.markerInfoWindowlistner=markerInfoWindow;
this.pubArrayList=pubArrayList;
clusterItemView = layoutInflater.inflate(R.layout.marker_info_window, null);
this.mapMarkerOnClickListener = mapMarkerOnClickListener;
this.googleMap=googleMap;
}
#Override
public View getInfoWindow(Marker marker) {
Log.i(TAG, "getInfoWindow: "+marker);
return null;
}
#Override
public View getInfoContents(Marker marker) {
Log.i(TAG, "getInfoContents: "+marker);
PubLocation pubLocation = (PubLocation) marker.getTag();
// googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(marker.getPosition(),13));
if (pubLocation == null) return clusterItemView;
TextView itemNameTextView = clusterItemView.findViewById(R.id.itemNameTextView);
TextView itemAddressTextView = clusterItemView.findViewById(R.id.itemAddressTextView);
ImageButton pub_info=(ImageButton)clusterItemView.findViewById(R.id.pub_info);
Button order_from_pub=(Button) clusterItemView.findViewById(R.id.order_from_pub);
this.infoButtonListener = new OnInfoWindowElemTouchListener(pub_info) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
Log.i(TAG, "onClickConfirmed: ");
Intent intent=new Intent(context,PubInfoActivity.class);
intent.putExtra(Constants.PUB_ID_KEY, pubLocation.getPubId());
context.startActivity(intent);
}
};
pub_info.setOnTouchListener(infoButtonListener);
this.orderFromPubListener = new OnInfoWindowElemTouchListener(order_from_pub) //btn_default_pressed_holo_light
{
#Override
protected void onClickConfirmed(View v, Marker marker) {
// Here we can perform some action triggered after clicking the button
for (int i = 0; i < pubArrayList.size(); i++) {
if (pubArrayList.get(i).getPubId().equals(pubLocation.getPubId())) {
mapMarkerOnClickListener.onMarkerClick(pubArrayList.get(i),v);
break;
}
}
}
};
order_from_pub.setOnTouchListener(orderFromPubListener);
itemNameTextView.setText(pubLocation.getTitle());
itemAddressTextView.setText(pubLocation.getSnippet());
markerInfoWindowlistner.setMarkerInfoWindow(clusterItemView,marker);
return clusterItemView;
}
}
Finally, got the solution to this issue
First set clustermanager to map as below:
getMap().setOnMarkerClickListener(mClusterManager);
On click of marker you just need to return true by adding one below condition and and pass zoom level to google map camera
mClusterManager.setOnClusterItemClickListener(new ClusterManager.OnClusterItemClickListener<PubLocation>() {
#Override
public boolean onClusterItemClick(PubLocation item) {
Log.i(TAG, "onClusterItemClick: ");
for (Marker marker : mClusterManager.getMarkerCollection().getMarkers()) {
if (marker.getPosition().latitude == item.getPosition().latitude &&
marker.getPosition().longitude == item.getPosition().longitude) {
marker.showInfoWindow();
}
}
CameraUpdate location = CameraUpdateFactory.newLatLngZoom(item.getPosition(), 10);
getMap().animateCamera(location, new GoogleMap.CancelableCallback() {
#Override
public void onFinish() {
getMap().animateCamera(CameraUpdateFactory.newLatLng(getMap().getProjection().fromScreenLocation(mappoint)));
}
#Override
public void onCancel() {
}
});
return true;
}
});

How to make custom info window in xamarin maps?

I want to create a custom info window in my Xamarin forms map,How can I implement this.I am using xamarin.forms.map map plugin to create map.
Please Help me
I want a custom info window like
this
i make custom map and custom pin
public class CustomMap : Map
{
public List<CustomPin> CustomPins { get; set; }
}
Custom Pin
public class CustomPin : Pin
{
public string ImageUrl { get; set; }
public float rating { get; set; }
}
Map page xaml.cs
public partial class MapPage : ContentPage
{
CustomPin pin;
MapVM MapVM;
public MapPage()
{
InitializeComponent();
pin = new CustomPin
{
Type = PinType.Place,
Position = new Position(37.79752, -122.40183),
Label = "Xamarin San Francisco Office",
Address = "394 Pacific Ave, San Francisco CA",
Url = "http://xamarin.com/about/",
rating = 3
};
var pin1 = new CustomPin
{
Type = PinType.Place,
Position = new Position(38.79752, -124.40183),
Label = "Xamarin San Francisco Office",
Address = "395 Pacific Ave, San Francisco CA",
Url = "http://xamarin.com/about/",
rating=2
};
customMap.CustomPins = new List<CustomPin> { pin, pin1 };
customMap.Pins.Add(pin);
customMap.Pins.Add(pin1);
customMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(37.79752, -122.40183), Distance.FromMiles(1.0)));
}
}
now i don't know about custom render class. please help me how i can define
custom render class and how i assign the image value and rating values to display in info window..
CustomRender.cs
[assembly: ExportRenderer(typeof(CustomMap), typeof(CustomMapRenderer))]
namespace CustomRenderer.Droid
{
public class CustomMapRenderer : MapRenderer, GoogleMap.IInfoWindowAdapter
{
List<CustomPin> customPins;
public CustomMapRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(Xamarin.Forms.Platform.Android.ElementChangedEventArgs<Map> e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
NativeMap.InfoWindowClick -= OnInfoWindowClick;
}
if (e.NewElement != null)
{
var formsMap = (CustomMap)e.NewElement;
customPins = formsMap.CustomPins;
Control.GetMapAsync(this);
}
}
protected override void OnMapReady(GoogleMap map)
{
base.OnMapReady(map);
NativeMap.InfoWindowClick += OnInfoWindowClick;
NativeMap.SetInfoWindowAdapter(this);
}
protected override MarkerOptions CreateMarker(Pin pin)
{
var marker = new MarkerOptions();
marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
marker.SetTitle(pin.Label);
marker.SetSnippet(pin.Address);
return marker;
}
public Android.Views.View GetInfoContents (Marker marker)
{
var inflater = Android.App.Application.Context.GetSystemService (Context.LayoutInflaterService) as Android.Views.LayoutInflater;
if (inflater != null) {
Android.Views.View view;
var customPin = GetCustomPin (marker);
if (customPin == null) {
throw new Exception ("Custom pin not found");
}
if (customPin.Id.ToString() == "Xamarin") {
view = inflater.Inflate (Resource.Layout.XamarinMapInfoWindow, null);
} else {
view = inflater.Inflate (Resource.Layout.MapInfoWindow, null);
}
var infoTitle = view.FindViewById<TextView> (Resource.Id.InfoWindowTitle);
var infoSubtitle = view.FindViewById<TextView(Resource.Id.InfoWindowSubtitle);
var imageView = view.FindViewById<ImageView>(Resource.Id.image);
var ratings = view.FindViewById<RatingBar>(Resource.Id.ratingbar);
//here how i set values for Image and Rating Cotrol
if (infoTitle != null) {
infoTitle.Text = marker.Title;
}
if (infoSubtitle != null) {
infoSubtitle.Text = marker.Snippet;
}
return view;
}
return null;
}
}
}
You can define a component that based on Xamarin.Forms component and you
can modify it like adding some bindable property,object etc. Also you can derive from a layout like stack , flow etc. instead of Xamarin.Forms component. Thus you can improve customizing level.
On Android side
[assembly: ExportRenderer(typeof(CustomEntry), typeof(AndroidCustomEntryRenderer))]
namespace MyProject.Droid.Renderer
{
public class AndroidCustomEntryRenderer : EntryRenderer
{
public AndroidCustomEntryRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
{
base.OnElementChanged(e);
if (Control != null)
{
Control.SetBackgroundColor(global::Android.Graphics.Color.White);
}
}
}
}
On PCL side
namespace MyProject.Views.ViewComponents
{
public class CustomEntry : Entry
{
}
}

Topshelf TimeoutException

I'm trying to use Topshelf Framework to create a windows service. But when i try to start the service, there is this exception :
" The service failed to start... System.Service.Process.TimeoutException : the waiting period has expired and the operation has not been completed"
This is my code :
public class MyService : ServiceControl
{
private System.Timers.Timer _timer;
public void MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = false;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
Thanks for any help :)
There are several issues I notice:
The current code would make the timer fire only once (you have AutoReset = false)
with TopShelf, the MyService class should look like this:
using System.Timers;
using Topshelf;
namespace TopShelfTestService
{
public class MyService
{
private System.Timers.Timer _timer;
public MyService()
{
_timer = new System.Timers.Timer(10);
_timer.AutoReset = true;
_timer.Elapsed += new ElapsedEventHandler(TimerOnElapsed);
}
private void TimerOnElapsed(object source, ElapsedEventArgs e)
{
//all the operation to do at the startup
}
public bool Start(HostControl hostControl)
{
_timer.Start();
return true;
}
public bool Stop(HostControl hostControl)
{
_timer.Stop();
return true;
}
}
}
and the console app/ Program.cs will look like so:
using Topshelf;
namespace TopShelfTestService
{
class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.Service<MyService>(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted((tc, hostControl) => tc.Start(hostControl));
s.WhenStopped((tc, hostControl) => tc.Stop(hostControl));
});
x.RunAsLocalSystem();
x.SetDescription("Sample Topshelf Host"); //7
x.SetDisplayName("Test Service with TopShelf"); //8
x.SetServiceName("TopShelfTestService");
});
}
}
}

sleep function not working correctly

I am using the code below to make my splash screen
package Splashscreentest;
/*
* SplashDemo.java
*
*/
import java.awt.*;
import java.awt.event.*;
public class Splashscreentest extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {"foo", "bar", "baz"};
g.setComposite(AlphaComposite.Clear);
g.fillRect(300,140,400,400);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString("Loading "+comps[(frame/5)%3]+"...", 120, 150);
}
public Splashscreentest() {
super("SplashScreen demo");
setSize(3000, 2000);
setLayout(new BorderLayout());
Menu m1 = new Menu("File");
MenuItem mi1 = new MenuItem("Exit");
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(5000);
}
catch(InterruptedException ex) {
}
}
splash.close();
setVisible(true);
toFront();
}
#Override
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static final WindowListener closeWindow = new WindowAdapter(){
#Override
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
}
}
The splash screen is not remaining on screen for the 5 seconds I would expect it to from the Thread.sleep command I used. The image for my splash screen is in this project within source packages
You're calling Thread.Sleep within the for loop. Change it to
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(50);
}
catch(InterruptedException ex) {
}
}

How to run a javaFX MediaPlayer in swing?

I've made a simple Media Player for an application I'm working on, the problem is that I thought that you could simply integrate JavaFX into Swing. Which is not the case. I have been searching for a solution to this problem and tried to use this website: http://docs.oracle.com/javafx/2/swing/jfxpub-swing.htm
The problem is that even though I have the website that explains how to put the code together, I still don't understand how. Here is the mediaplayer and I plan to integrate it into my Swing code, so that I can call the media player when a button is clicked. Here is all my code for the media player and if anyone can share some light on how to integrate it into my Swing code i.e my GUI, I would probably have to kiss you through the computer.
public class Player extends Application{
private boolean atEndOfMedia = false;
private final boolean repeat = false;
private boolean stopRequested = false;
private Duration duration;
private Label playTime;
private Slider volumeSlider;
#Override
public void start(final Stage stage) throws Exception {
stage.setTitle("Movie Player");//set title
Group root = new Group();//Group for buttons etc
final Media media = new Media("file:///Users/Paul/Downloads/InBruges.mp4");
final MediaPlayer playa = new MediaPlayer(media);
MediaView view = new MediaView(playa);
//Slide in and out and what causes that.
final Timeline slideIn = new Timeline();
final Timeline slideOut = new Timeline();
root.setOnMouseEntered(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(MouseEvent t) {
slideIn.play();
}
});
root.setOnMouseExited(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(MouseEvent t) {
slideOut.play();
}
});
final VBox vbox = new VBox();
final Slider slider = new Slider();
final Button playButton = new Button("|>");
root.getChildren().add(view);
root.getChildren().add(vbox);
vbox.getChildren().add(slider);
vbox.getChildren().add(playButton);
vbox.setAlignment(Pos.CENTER);
Scene scene = new Scene(root, 400, 400, Color.BLACK);
stage.setScene(scene);
stage.show();
// Play/Pause Button
playButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
Status status = playa.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED)
{
// don't do anything in these states
return;
}
if ( status == Status.PAUSED
|| status == Status.READY
|| status == Status.STOPPED)
{
// rewind the movie if we're sitting at the end
if (atEndOfMedia) {
playa.seek(playa.getStartTime());
atEndOfMedia = false;
}
playa.play();
} else {
playa.pause();
}
}
});
//Listeners and Shit for Play Button
playa.setOnPlaying(new Runnable() {
#Override
public void run() {
if (stopRequested) {
playa.pause();
stopRequested = false;
} else {
playButton.setText("||");
}
}
});
playa.setOnPaused(new Runnable() {
#Override
public void run() {
playButton.setText(">");
}
});
playa.play();
playa.setOnReady(new Runnable() {
#Override
public void run(){
int v = playa.getMedia().getWidth();
int h = playa.getMedia().getHeight();
stage.setMinWidth(v);
stage.setMinHeight(h);
vbox.setMinSize(v, 100);
vbox.setTranslateY(h-50);
//slider and graphical slide in/out
slider.setMin(0.0);
slider.setValue(0.0);
slider.setMax(playa.getTotalDuration().toSeconds());
slideOut.getKeyFrames().addAll(
new KeyFrame(new Duration(0),
new KeyValue(vbox.translateYProperty(), h-100),
new KeyValue(vbox.opacityProperty(), 0.9)
),
new KeyFrame(new Duration(300),
new KeyValue(vbox.translateYProperty(), h),
new KeyValue(vbox.opacityProperty(), 0.0)
)
);
slideIn.getKeyFrames().addAll(
new KeyFrame(new Duration(0),
new KeyValue(vbox.translateYProperty(), h),
new KeyValue(vbox.opacityProperty(), 0.0)
),
new KeyFrame(new Duration(300),
new KeyValue(vbox.translateYProperty(), h-100),
new KeyValue(vbox.opacityProperty(), 0.9)
)
);
}
});
//Slider being current and ability to click on slider.
playa.currentTimeProperty().addListener(new ChangeListener<Duration>(){
#Override
public void changed(ObservableValue<? extends Duration> observableValue, Duration duration, Duration current){
slider.setValue(current.toSeconds());
}
});
slider.setOnMouseClicked(new javafx.event.EventHandler<javafx.scene.input.MouseEvent>() {
#Override
public void handle(javafx.scene.input.MouseEvent t) {
playa.seek(Duration.seconds(slider.getValue()));
}
});
}
Use JFXPanel:
public class Test {
private static void initAndShowGUI() {
// This method is invoked on Swing thread
JFrame frame = new JFrame("FX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setVisible(true);
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
}
private static void initFX(JFXPanel fxPanel) {
// This method is invoked on JavaFX thread
Scene scene = createScene();
fxPanel.setScene(scene);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
initAndShowGUI();
}
});
}
}
where method createScene() is start(final Stage stage) from your code.
Just instead of putting scene to stage you return it.