when I press the Start button on the Night screen and return to it, the Night screen is not maintained. How can I maintain it?
enter image description here
enter image description here
when I press the "Start button" on the "Night screen" and come back, the "Morning screen" appears.
How do i make the "Night screen" appear even when I return after pressing the button?
package kr.ac.mjc.ict2018261001.airhockey;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
import kr.ac.mjc.ict2018261001.airhockey.Themes.OnSwipeTouchListener;
import kr.ac.mjc.ict2018261001.airhockey.Themes.ThemeUtil;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
TextView textView;
int count = 0;
String themeColor;
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseAuth firebaseAuth = FirebaseAuth.getInstance();
#SuppressLint("ClickableViewAccessibility")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button startBtn = findViewById(R.id.start_btn);
imageView = findViewById(R.id.imageView);
textView = findViewById(R.id.textView);
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
}
});
imageView.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
public void onSwipeTop() {
}
public void onSwipeRight() {
if (count == 0) {
imageView.setImageResource(R.drawable.good_night_img);
textView.setText("Night");
count = 1;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.DARK_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
} else {
imageView.setImageResource(R.drawable.good_morning_img);
textView.setText("Morning");
count = 0;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.LIGHT_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
}
}
public void onSwipeLeft() {
if (count == 0) {
imageView.setImageResource(R.drawable.good_night_img);
textView.setText("Night");
count = 1;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.DARK_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
} else {
imageView.setImageResource(R.drawable.good_morning_img);
textView.setText("Morning");
count = 0;
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,NumberActivity.class);
startActivity(intent);
themeColor = ThemeUtil.LIGHT_MODE;
ThemeUtil.applyTheme(themeColor);
ThemeUtil.modSave(getApplicationContext(),themeColor);
}
});
}
}
public void onSwipeBottom() {
}
});
FirebaseDatabase database = FirebaseDatabase.getInstance();
}
}
package kr.ac.mjc.ict2018261001.airhockey.Themes;
import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context ctx){
gestureDetector = new GestureDetector(ctx, new GestureListener());
}
#Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
#Override
public boolean onDown(MotionEvent e) {
return true;
}
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
boolean result = false;
try {
float diffY = e2.getY() - e1.getY();
float diffX = e2.getX() - e1.getX();
if (Math.abs(diffX) > Math.abs(diffY)) {
if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (diffX > 0) {
onSwipeRight();
} else {
onSwipeLeft();
}
result = true;
}
}
else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
if (diffY > 0) {
onSwipeBottom();
} else {
onSwipeTop();
}
result = true;
}
} catch (Exception exception) {
exception.printStackTrace();
}
return result;
}
}
public void onSwipeRight() {
}
public void onSwipeLeft() {
}
public void onSwipeTop() {
}
public void onSwipeBottom() {
}
}
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();
}
}
How to do drag and drop within one listview
I have only one list view (Ed. "player")
My requirement is to move up and down in the same player list
Please find the code i have used
(Not: I am using jdk 1.7 with default javafx)
Example:(player = listView)
listView.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
Dragboard dragBoard = listView.startDragAndDrop(TransferMode.MOVE);
ClipboardContent content = new ClipboardContent();
content.putString(listView.getSelectionModel().getSelectedItem().getValue());
dragBoard.setContent(content);
}
});
listView.setOnDragDone(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragDone left");
}
});
listView.setOnDragEntered(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragEntered left");
}
});
listView.setOnDragExited(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragExited left");
listView.setBlendMode(null);
}
});
listView.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
System.out.println("setOnDragOver left");
dragEvent.acceptTransferModes(TransferMode.MOVE);
}
});
listView.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent dragEvent) {
String context = dragEvent.getDragboard().getString();
dragEvent.setDropCompleted(true);
}
}
});
I am new to javafx
Would you please help on this regard
Don't register the drag handlers on the ListView: you will have no way of knowing which cells the drag started and ended on. Instead, you need to register the handlers on the cells. The details get a little tricky, but the basic idea is to create a cell factory in which you create the custom cells; here you can set up the drag and drop handlers.
Here's an example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import javafx.util.Callback;
public class DragAndDropListView extends Application {
#Override
public void start(Stage primaryStage) {
final ListView<String> listView = new ListView<>();
for (int i=1; i<=20; i++) {
listView.getItems().add("Item "+i);
}
final IntegerProperty dragFromIndex = new SimpleIntegerProperty(-1);
listView.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> lv) {
final ListCell<String> cell = new ListCell<String>() {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
} else {
setText(item);
}
}
};
cell.setOnDragDetected(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
if (! cell.isEmpty()) {
dragFromIndex.set(cell.getIndex());
Dragboard db = cell.startDragAndDrop(TransferMode.MOVE);
ClipboardContent cc = new ClipboardContent();
cc.putString(cell.getItem());
db.setContent(cc);
// Java 8 only:
// db.setDragView(cell.snapshot(null, null));
}
}
});
cell.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
if (dragFromIndex.get() >= 0 && dragFromIndex.get() != cell.getIndex()) {
event.acceptTransferModes(TransferMode.MOVE);
}
}
});
// highlight drop target by changing background color:
cell.setOnDragEntered(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
if (dragFromIndex.get() >= 0 && dragFromIndex.get() != cell.getIndex()) {
// should really set a style class and use an external style sheet,
// but this works for demo purposes:
cell.setStyle("-fx-background-color: gold;");
}
}
});
// remove highlight:
cell.setOnDragExited(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
cell.setStyle("");
}
});
cell.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
int dragItemsStartIndex ;
int dragItemsEndIndex ;
int direction ;
if (cell.isEmpty()) {
dragItemsStartIndex = dragFromIndex.get();
dragItemsEndIndex = listView.getItems().size();
direction = -1;
} else {
if (cell.getIndex() < dragFromIndex.get()) {
dragItemsStartIndex = cell.getIndex();
dragItemsEndIndex = dragFromIndex.get() + 1 ;
direction = 1 ;
} else {
dragItemsStartIndex = dragFromIndex.get();
dragItemsEndIndex = cell.getIndex() + 1 ;
direction = -1 ;
}
}
List<String> rotatingItems = listView.getItems().subList(dragItemsStartIndex, dragItemsEndIndex);
List<String> rotatingItemsCopy = new ArrayList<>(rotatingItems);
Collections.rotate(rotatingItemsCopy, direction);
rotatingItems.clear();
rotatingItems.addAll(rotatingItemsCopy);
dragFromIndex.set(-1);
}
});
cell.setOnDragDone(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
dragFromIndex.set(-1);
listView.getSelectionModel().select(event.getDragboard().getString());
}
});
return cell ;
}
});
BorderPane root = new BorderPane();
root.setCenter(listView);
Scene scene = new Scene(root, 250, 400);
scene.getStylesheets().add(getClass().getResource("drag-and-drop-list.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
This will enable you to drag any element and drop it onto any other. For example dragging the third item in the list
and dropping it on the first item results in this:
In Java 8 you can also add the line
db.setDragView(cell.snapshot(null, null));
to the setOnDragDetected(...) method to get a better visual on the drag.
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 am trying to get my head around the JavaFX stuff...
My program is a WindowBuilder based Gui, and I want a JavaFX graph, and a JavaFX live video-feed displayed in my app.
How do I implement it in my code? I have tried this, but I couldn't get it runnning.
The data feed isnt the problem. I just need to view it inside my JFrame as small squares...
Confused now :(
Here is my code: (I am sorry that it is a tad long, but I blame the examplecode from JavaFX :p
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Canvas;
import java.awt.SystemColor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import javax.swing.UIManager.*;
/**
* #author
*
*/
public class MyClientApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static final String BufferedWriter = null;
JFrame frame;
private JTextField textFieldUsername;
/**
* Create the application.
*/
public MyClientApp(BufferedWriter serverDataOut, BufferedReader serverDataIn) {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #param serverDataOut
*
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// Nimbus Theme not avaliable
}
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("*********** My Program ***********");
frame.setBounds(320, 130, 730, 570);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Canvas canvasTemp = new Canvas();
canvasTemp.setBackground(SystemColor.window);
canvasTemp.setBounds(6, 277, 380, 255);
frame.getContentPane().add(canvasTemp);
Canvas canvasLevel = new Canvas();
canvasLevel.setBackground(SystemColor.window);
canvasLevel.setBounds(6, 10, 380, 255);
frame.getContentPane().add(canvasLevel);
}
public JFrame frame() {
return frame;
}
}
And here is the main file to get it running for you guys... :
Client.java
import java.io.IOException;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
MyClientApp window = new MyClientApp(null, null);
window.frame.setVisible(true);
}
}
The code I want to implement is:
AdvancedLineChartSample.java (from JavaFX)
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.util.Duration;
/**
* An advanced line chart with a variety of actions and settable properties.
*
* #see javafx.scene.chart.LineChart
* #see javafx.scene.chart.Chart
* #see javafx.scene.chart.NumberAxis
* #see javafx.scene.chart.XYChart
*/
public class AdvancedLineChartSample extends Application {
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
}
protected LineChart<Number, Number> createChart() {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<Number,Number> lc = new LineChart<Number,Number>(xAxis,yAxis);
// setup chart
lc.setTitle("Temp Chart");
xAxis.setLabel("tid");
yAxis.setLabel("temp");
// add starting data
XYChart.Series<Number,Number> series = new XYChart.Series<Number,Number>();
series.setName("Dataset 1");
series.getData().add(new XYChart.Data<Number,Number>(20d, 50d));
series.getData().add(new XYChart.Data<Number,Number>(40d, 80d));
series.getData().add(new XYChart.Data<Number,Number>(50d, 90d));
series.getData().add(new XYChart.Data<Number,Number>(70d, 30d));
series.getData().add(new XYChart.Data<Number,Number>(170d, 122d));
lc.getData().add(series);
return lc;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
and the StreamingMediaPlayer.java (from JavaFX):
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.animation.ParallelTransition;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
/**
* A media player with controls for play, pause, stop, seek, and volume. This media player is playing media via HTTP Live Streaming, also known as HLS.
*
* #see javafx.scene.media.MediaPlayer
* #see javafx.scene.media.Media
*/
public class StreamingMediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/JavaRap/prog_index.m3u8";
private MediaPlayer mediaPlayer;
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
mediaPlayer.setAutoPlay(true);
PlayerPane playerPane = new PlayerPane(mediaPlayer);
playerPane.setMinSize(480, 360);
playerPane.setPrefSize(480, 360);
playerPane.setMaxSize(480, 360);
// getStylesheets().add("ensemble/samples/media/OverlayMediaPlayer.css");
root.getChildren().add(playerPane);
}
public void play() {
Status status = mediaPlayer.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED) {
return;
}
if (status == Status.PAUSED || status == Status.STOPPED || status == Status.READY) {
mediaPlayer.play();
}
}
#Override public void stop() {
mediaPlayer.stop();
}
static class PlayerPane extends BorderPane {
private MediaPlayer mp;
private MediaView mediaView;
private final boolean repeat = false;
private boolean stopRequested = false;
private boolean atEndOfMedia = false;
private Duration duration;
private Slider timeSlider;
private Label playTime;
private Slider volumeSlider;
private HBox mediaTopBar;
private HBox mediaBottomBar;
private ParallelTransition transition = null;
#Override protected void layoutChildren() {
if (mediaView != null && getBottom() != null) {
mediaView.setFitWidth(getWidth());
mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
}
super.layoutChildren();
if (mediaView != null) {
mediaView.setTranslateX((((Pane)getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
mediaView.setTranslateY((((Pane)getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
}
}
#Override protected double computeMinWidth(double height) {
return mediaBottomBar.prefWidth(-1);
}
#Override protected double computeMinHeight(double width) {
return 200;
}
#Override protected double computePrefWidth(double height) {
return Math.max(mp.getMedia().getWidth(), mediaBottomBar.prefWidth(height));
}
#Override protected double computePrefHeight(double width) {
return mp.getMedia().getHeight() + mediaBottomBar.prefHeight(width);
}
#Override protected double computeMaxWidth(double height) { return Double.MAX_VALUE; }
#Override protected double computeMaxHeight(double width) { return Double.MAX_VALUE; }
public PlayerPane(final MediaPlayer mp) {
this.mp = mp;
setId("player-pane");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() { };
mvPane.setId("media-pane");
mvPane.getChildren().add(mediaView);
setCenter(mvPane);
mediaTopBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaTopBar, Pos.CENTER);
mediaBottomBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaBottomBar, Pos.CENTER);
mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
updateValues();
}
});
mp.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
mp.pause();
stopRequested = false;
}
}
});
mp.setOnReady(new Runnable() {
public void run() {
duration = mp.getMedia().getDuration();
updateValues();
}
});
mp.setOnEndOfMedia(new Runnable() {
public void run() {
if (!repeat) {
stopRequested = true;
atEndOfMedia = true;
}
}
});
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
// Time label
Label timeLabel = LabelBuilder.create()
.text("Time")
.minWidth(Control.USE_PREF_SIZE)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(timeLabel);
// Time slider
timeSlider = SliderBuilder.create()
.id("media-slider")
.minWidth(240)
.maxWidth(Double.MAX_VALUE)
.build();
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position
if (duration != null) {
mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
}
updateValues();
}
}
});
HBox.setHgrow(timeSlider, Priority.ALWAYS);
mediaTopBar.getChildren().add(timeSlider);
// Play label
playTime = LabelBuilder.create()
.prefWidth(130)
.minWidth(50)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(playTime);
// Volume label
Label volumeLabel = LabelBuilder.create()
.text("Vol")
.textFill(Color.WHITE)
.minWidth(Control.USE_PREF_SIZE)
.build();
mediaTopBar.getChildren().add(volumeLabel);
// Volume slider
volumeSlider = SliderBuilder.create()
.id("media-slider")
.prefWidth(120)
.maxWidth(Region.USE_PREF_SIZE)
.minWidth(30)
.build();
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
}
});
volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
}
}
});
mediaTopBar.getChildren().add(volumeSlider);
setTop(mediaTopBar);
final EventHandler<ActionEvent> backAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.seek(Duration.ZERO);
}
};
final EventHandler<ActionEvent> stopAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.stop();
}
};
final EventHandler<ActionEvent> playAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.play();
}
};
final EventHandler<ActionEvent> pauseAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.pause();
}
};
final EventHandler<ActionEvent> forwardAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Duration currentTime = mp.getCurrentTime();
mp.seek(Duration.seconds(currentTime.toSeconds() + 5.0));
}
};
mediaBottomBar = HBoxBuilder.create()
.id("bottom")
.spacing(0)
.alignment(Pos.CENTER)
.children(
ButtonBuilder.create()
.id("back-button")
.text("Back")
.onAction(backAction)
.build(),
ButtonBuilder.create()
.id("stop-button")
.text("Stop")
.onAction(stopAction)
.build(),
ButtonBuilder.create()
.id("play-button")
.text("Play")
.onAction(playAction)
.build(),
ButtonBuilder.create()
.id("pause-button")
.text("Pause")
.onAction(pauseAction)
.build(),
ButtonBuilder.create()
.id("forward-button")
.text("Forward")
.onAction(forwardAction)
.build()
)
.build();
setBottom(mediaBottomBar);
}
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration. greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
}
if (!volumeSlider.isValueChanging()) {
volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
}
}
});
}
}
private static String formatTime(Duration elapsed, Duration duration) {
int intElapsed = (int)Math.floor(elapsed.toSeconds());
int elapsedHours = intElapsed / (60 * 60);
if (elapsedHours > 0) {
intElapsed -= elapsedHours * 60 * 60;
}
int elapsedMinutes = intElapsed / 60;
int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;
if (duration.greaterThan(Duration.ZERO)) {
int intDuration = (int)Math.floor(duration.toSeconds());
int durationHours = intDuration / (60 * 60);
if (durationHours > 0) {
intDuration -= durationHours * 60 * 60;
}
int durationMinutes = intDuration / 60;
int durationSeconds = intDuration - durationHours * 60 * 60 - durationMinutes * 60;
if (durationHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
}
}
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args);
}
}
I'm sorry about the long code. Its just the samplecode from JavaFX. You find it here, and here.
That should be quite easy to solve. Let me explain it with the chart example that you've shown.
Add an instance of JFXPanel to your JFrame. In your examples, all components are added to a Stage, which is the JavaFX class to represent a window. So you don't need it here. Instead, you add the components that you want to use to the JFXPanel. See also here (function initAndShowGUI) how to do it.
In the init function of the example, a Scene is created as well as the chart itself. What you have to do to let the chart be shown is not much more than that - create a Scene, fill it with content and pass it to the JFXPanel that you already created.
With a minimum effort you can make your chart example run: Make sure that AdvancedLineChartSample.java is in your build path and that the function createChart is somehow accessible from your JFrame. Then add the chart to your code with something similar to the following snippet.
Group root=new Group();
Scene scene=new Scene(root);
myJFXPanel.setScene(scene);
root.getChildren().add(createChart());
This is just a very quick and dirty solution to run your example without any beautiful code and also I didn't test it. But hopefully it gives you a basic understanding of what's going on to encourage further experiments. By my own experience I can tell you that from this step on, there's a lot of fun to come with JavaFX 2.