I am building an android GPS app with Codename one. I use com.codename1.googlemaps.MapContainer to create a Google map;
In my app is use tabs to create different "pages".
Code:
cnt = new MapContainer();
t.addTab("Tab3", cnt);
And for my current location I use:
try {
Coord position = new Coord(lat,lng);
cnt.clearMapLayers();
cnt.setCameraPosition(position);
cnt.addMarker(EncodedImage.create("/maps-pin.png"), position, "Hi marker", "Optional long description", new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// stuff todo...
}
});
} catch(IOException err) {
// since the image is iin the jar this is unlikely
err.printStackTrace();
}
I like to add a wms layer to the Google Maps. Is this possible? I can't find in codenameone a command addLayer. If yes, do you have a code snippet how to do this?
If it is not possiple, can I use openlayers in my codename one app? Can you give me a code snippet to do this?
Edit
I started to create an native file to "catch"the addtileoverlay from google maps api. The layer I want to use is a xyz layer, so I think I can use a urltileprovider from the googlemap api
I made the native code for the tileoverlay but the tileoverlay doesn't appear. Is it because i didn't get a link with the mapcontainer.
I am little bit stuck. I tried to build from scratch with the googmaps example but the mapcompnent is not anymore used.
package com.Bellproductions.TalkingGps;
import com.google.android.gms.maps.model.UrlTileProvider;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.TileOverlayOptions;
import com.google.android.gms.maps.model.TileProvider;
import com.google.android.gms.maps.model.TileOverlay;
import com.codename1.impl.android.AndroidNativeUtil;
import java.util.Locale;
import java.net.MalformedURLException;
public class SeamarksImpl {
private GoogleMap mapInstance;
private TileOverlay m;
TileProvider provider;
public boolean isSupported() {
return true;
}
public long addTilelayer (){
final String URL_FORMAT = "http://t1.openseamap.org/seamark/{z}/{x}/{y}.png";
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
provider = new UrlTileProvider(256, 256) {
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
try {
y = (1 << zoom) - y - 1;
return new URL(String.format(Locale.US, URL_FORMAT, zoom, x, y ));
} catch (MalformedURLException e) {
throw new RuntimeException();
}
}
TileOverlayOptions tileopt = new TileOverlayOptions().tileProvider(provider);
public void addlayer() {
m = mapInstance.addTileOverlay(tileopt);
}
};
}
});
long p = 1;
return p;}
}
My seamarks.java file has this code to bind with the native interface
import com.codename1.system.NativeInterface;
/**
*
* #author Hongerige Wolf
*/
public interface Seamarks extends NativeInterface {
public void addTilelayer ();
}
In the mainactivity java file i have the statements
public Seamarks seamark;
public void init(Object context) {
seamark = (Seamarks)NativeLookup.create(Seamarks.class);
}
public void start() {
seamark.addTilelayer();
}
Update
I created a new googlemaps.CN1lib. But the xyz layer is not showing on the googlemaps. I used native code tot use the Tileoverlay feature and tried to add tileoverlay in the same way as Markers.
In the InternalNativeMapsImpl file i changed
private void installListeners() {
/*
if (mapInstance == null) {
view = null;
System.out.println("Failed to get map instance, it seems google play services are not installed");
return;
}*/
view.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
mapInstance = googleMap;
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
String tileLayer= "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
//String s = String.format(Locale.US, tileLayer , zoom, x, y);
String s = tileLayer + "/" + zoom + "/" + x + "/" + reversedY + ".png";
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
mapInstance.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
public boolean onMarkerClick(Marker marker) {
Long val = listeners.get(marker);
if (val != null) {
MapContainer.fireMarkerEvent(InternalNativeMapsImpl.this.mapId, val.longValue());
return true;
}
return false;
}
});
mapInstance.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
public void onCameraChange(CameraPosition position) {
MapContainer.fireMapChangeEvent(InternalNativeMapsImpl.this.mapId, (int) position.zoom, position.target.latitude, position.target.longitude);
}
});
mapInstance.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
public void onMapClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireTapEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
public void onMapLongClick(LatLng point) {
Point p = mapInstance.getProjection().toScreenLocation(point);
MapContainer.fireLongPressEventStatic(InternalNativeMapsImpl.this.mapId, p.x, p.y);
}
});
mapInstance.setMyLocationEnabled(showMyLocation);
mapInstance.getUiSettings().setRotateGesturesEnabled(rotateGestureEnabled);
}
});
}
Secondly i added a addTilexyz method also in the same way as addMarkers
public long addTilexyz(final String Turl) {
uniqueIdCounter++;
final long key = uniqueIdCounter;
AndroidNativeUtil.getActivity().runOnUiThread(new Runnable() {
public void run() {
TileProvider tileProvider;
tileProvider = new UrlTileProvider(256, 256) {
// Tileurl = "http://t1.openseamap.org/seamark/";
#Override
public synchronized URL getTileUrl(int x, int y, int zoom) {
// The moon tile coordinate system is reversed. This is not normal.
int reversedY = (1 << zoom) - y - 1;
String s = String.format(Locale.US, Turl , zoom, x, reversedY);
URL url = null;
try {
url = new URL(s);
} catch (MalformedURLException e) {
throw new AssertionError(e);
}
return url;
}
};
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
}
});
return key;
}
In the InternalNativeMaps file i added te method
public long addTilexyz(String Turl);
And in the Mapcontainer file i added
public MapObject addTilexyz(String Turl) {
if(internalNative != null) {
MapObject o = new MapObject();
Long key = internalNative.addTilexyz(Turl);
o.mapKey = key;
markers.add(o);
return o;
} else {
}
MapObject o = new MapObject();
return o;
}
I am puzzeled what is wrong with the code. I wonder if the commands
Long key = internalNative.addTilexyz(Turl);
and
mMoonTiles = mapInstance.addTileOverlay(new TileOverlayOptions().tileProvider(tileProvider));
put the tileoverlay on the googlemap. Or is the tileurl wrong. http://t1.openseamap.org/seamark/z/x/y.png is correct.
We don't expose layers in the native maps at this time, you can fork the project and just add an API to support that to the native implementations.
Related
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;
}
});
Currently, the PopupMenu will show up when I right-click on the TrayIcon in the SystemTray. However, I want it to do the same when I left-click on the TrayIcon.
I thought I might accomplish this by using a mouseListener on the TrayIcon, but I don't know what method to invoke in the mouseClicked event to achieve the desired results.
icon = new TrayIcon(img, tooltip, popup);
icon.addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
popup.setEnabled(true);
}
});
Using the setEnabled() method does not make the popup menu appear when I left-click the TrayIcon. It actually has no noticeable effect. I'm wondering what method I should use in the mouseClicked() body in order to make the popup show up when it is left-clicked.
Basically, in your mouse listener, you need to determine which button was pressed (and optional, how many times).
The critical piece of code is this...
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) { ... }
I've also included some additional code that makes sure the popup does not cover the task bar and is displayed within the viewable area of the screen (it's a nit pick of mine ;))
public class TestTrayIcon02 {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ex) {
}
try {
final TrayIcon ti = new TrayIcon(ImageIO.read(getClass().getResource("/Smiley.png")), "Have a nice day");
final JPopupMenu popup = new JPopupMenu();
JMenuItem mi = new JMenuItem("Get me some");
mi.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
SystemTray.getSystemTray().remove(ti);
System.exit(0);
}
});
popup.add(mi);
ti.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 1) {
Rectangle bounds = getSafeScreenBounds(e.getPoint());
Point point = e.getPoint();
int x = point.x;
int y = point.y;
if (y < bounds.y) {
y = bounds.y;
} else if (y > bounds.y + bounds.height) {
y = bounds.y + bounds.height;
}
if (x < bounds.x) {
x = bounds.x;
} else if (x > bounds.x + bounds.width) {
x = bounds.x + bounds.width;
}
if (x + popup.getPreferredSize().width > bounds.x + bounds.width) {
x = (bounds.x + bounds.width) - popup.getPreferredSize().width;
}
if (y + popup.getPreferredSize().height > bounds.y + bounds.height) {
y = (bounds.y + bounds.height) - popup.getPreferredSize().height;
}
popup.setLocation(x, y);
popup.setVisible(true);
}
}
});
SystemTray.getSystemTray().add(ti);
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static Rectangle getSafeScreenBounds(Point pos) {
Rectangle bounds = getScreenBoundsAt(pos);
Insets insets = getScreenInsetsAt(pos);
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
return bounds;
}
public static Insets getScreenInsetsAt(Point pos) {
GraphicsDevice gd = getGraphicsDeviceAt(pos);
Insets insets = null;
if (gd != null) {
insets = Toolkit.getDefaultToolkit().getScreenInsets(gd.getDefaultConfiguration());
}
return insets;
}
public static Rectangle getScreenBoundsAt(Point pos) {
GraphicsDevice gd = getGraphicsDeviceAt(pos);
Rectangle bounds = null;
if (gd != null) {
bounds = gd.getDefaultConfiguration().getBounds();
}
return bounds;
}
public static GraphicsDevice getGraphicsDeviceAt(Point pos) {
GraphicsDevice device = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice lstGDs[] = ge.getScreenDevices();
ArrayList<GraphicsDevice> lstDevices = new ArrayList<GraphicsDevice>(lstGDs.length);
for (GraphicsDevice gd : lstGDs) {
GraphicsConfiguration gc = gd.getDefaultConfiguration();
Rectangle screenBounds = gc.getBounds();
if (screenBounds.contains(pos)) {
lstDevices.add(gd);
}
}
if (lstDevices.size() > 0) {
device = lstDevices.get(0);
} else {
device = ge.getDefaultScreenDevice();
}
return device;
}
}
What you're trying to do is apparently not possible:
You cannot show the PopupMenu with its show method since you need to specify a JComponent but your TrayIcon isn't one (weird enough though that TrayIcon still manages to do it, so apparently there is a way, don't ask me though..). So, as MadProgrammer suggested, you should try using JPopupMenu instead. Don't add it to your TrayIcon for that won't be possible, but display your JPopupMenu by adding a MouseListener to your TrayIcon. That should do the trick:
final TrayIcon tray = new TrayIcon( img, tooltip, null);
final JPopupMenu menu = new JPopupMenu();
... // your menu initialization.
tray.addMouseListener( new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent evt) {
menu.setLocation( evt.getPoint() );
menu.setVisible( true );
}
}
I'm able to update the TableModel using setValueAt() but changes are not visible in the Table
below is the code:
import javax.swing.JFrame;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import java.awt.Dimension;
import java.awt.GridLayout;
public class TableFTFEditDemo extends JPanel {
private boolean DEBUG = true;
JTable table;
MyTableModel tableModel=new MyTableModel();
public TableFTFEditDemo() {
super(new GridLayout(1,0));
table = new JTable(tableModel);
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
//Create the scroll pane and add the table to it.
JScrollPane scrollPane = new JScrollPane(table);
//Set up stricter input validation for the integer column.
table.setDefaultEditor(Integer.class,
new IntegerEditor(0, 100));
//If we didn't want this editor to be used for other
//Integer columns, we'd do this:
//table.getColumnModel().getColumn(3).setCellEditor(
// new IntegerEditor(0, 100));
//Add the scroll pane to this panel.
add(scrollPane);
}
class MyTableModel extends AbstractTableModel {
private String[] columnNames ;
private Object[][] data;
MyTableModel(){
columnNames=new String[] {"First Name","Last Name","Sport","# of Seaters","Vegetarian","blank"};
data=new Object[][] {
{"Kathy", "Smith",
"Snowboarding", new Integer(5), new Boolean(false),"sdf"},
{"John", "Doe",
"Rowing", new Integer(3), new Boolean(true),"reytry"},
{"Sue", "Black",
"Knitting", new Integer(2), new Boolean(false),"wwttu"},
{"Jane", "White",
"Speed reading", new Integer(20), new Boolean(true),"yuiyio"},
{"Joe", "Brown",
"Pool", new Integer(10), new Boolean(false),"ertey"}
};
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.length;
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
return data[row][col];
}
/*
* JTable uses this method to determine the default renderer/
* editor for each cell. If we didn't implement this method,
* then the last column would contain text ("true"/"false"),
* rather than a check box.
*/
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public boolean isCellEditable(int row, int col) {
//Note that the data/cell address is constant,
//no matter where the cell appears onscreen.
if (col < 2) {
return false;
} else {
return true;
}
}
public void setValueAt(Object value, int row, int col) {
if (DEBUG) {
System.out.println("Setting value at " + row + "," + col
+ " to " + value
+ " (an instance of "
+ value.getClass() + ")");
}
data[row][col] = value;
this.fireTableCellUpdated(row,col);
if (DEBUG) {
System.out.println("New value of data:");
printDebugData();
}
}
private void printDebugData() {
int numRows = getRowCount();
int numCols = getColumnCount();
for (int i=0; i < numRows; i++) {
System.out.print(" row " + i + ":");
for (int j=0; j < numCols; j++) {
System.out.print(" " + data[i][j]);
}
System.out.println();
}
System.out.println("--------------------------");
}
}
/**
* Create the GUI and show it. For thread safety,
* this method should be invoked from the
* event-dispatching thread.
*/
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("TableFTFEditDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Create and set up the content pane.
TableFTFEditDemo newContentPane = new TableFTFEditDemo();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
//Schedule a job for the event-dispatching thread:
//creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
void runtable(){
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
tableModel.setValueAt(new Integer(5),2,5);
((AbstractTableModel)table.getModel()).fireTableCellUpdated(2,5);
}
});
}
/** using this to call setValueAt from other classes*/
public void setValueAt1(Object value, int row, int col) {
table.setValueAt(new Integer(5),row,col);
((AbstractTableModel)table.getModel()).fireTableCellUpdated(row,col);
}
}
PS: the code is taken frm oracle' example..i just want to knw how to reflect the changes made in tablemodel in the table.
Your code works as expected, just you do not actually call setValueAt() on your model. Your runtable() method where you do is never invoked.
To verify, change createAndShowGUI() to return the newContentPane and use the following main:
static TableFTFEditDemo instance;
public static void main(String[] args) throws Exception {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
instance = createAndShowGUI();
}
});
Thread.sleep(5000);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
instance.tableModel.setValueAt(5, 2, 5);
}
});
}
After the programmed five second delay, the value in column 2 row five will change from "wwtu" into "5".
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.
I have to implement 4 functionalities on my GUI. Functionalities are exclusive. Each functionality can have several commands that the user can execute. All this must be represented with icons and buttons only in a toolbar. I'm searching example and ideas to create this kind of toolbar.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MultiToolBar {
private static void addButtons(Container c, int i, JButton[] b) {
int startAt = (i==0 ? 0 : i*3);
int endAt = startAt+3;
for (int ii = startAt; ii<endAt; ii++) {
c.add(b[ii]);
}
c.validate();
}
public static void main(String[] args) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
final JToolBar tb = new JToolBar();
final JButton[] buttons = new JButton[12];
for (int ii=0; ii<buttons.length; ii++) {
buttons[ii] = new JButton("Button " + (ii+1));
}
String[] functions = new String[4];
for (int ii=0; ii<functions.length; ii++) {
functions[ii] = "Function " + (ii+1);
}
final JComboBox cb = new JComboBox(functions);
tb.add(cb);
cb.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent lse) {
Component[] components = tb.getComponents();
for (Component component : components) {
if (!(component instanceof JComboBox)) {
tb.remove(component);
}
}
int index = cb.getSelectedIndex();
addButtons(tb, index, buttons);
}
});
cb.setSelectedIndex(3);
JOptionPane.showMessageDialog(null, tb);
}
});
}
}
Take a look at the class JToolBar, here is a good tutorial from Oracle.
Oracle - How to Use Toolbars