Screenshot saving error JavaFX - javafx

I am trying to save a screenshot of the current scene using javaFX.
saveMenuItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
WritableImage image = scene.snapshot(new SnapshotParameters(), null);
// TODO: probably use a file chooser here
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Save Image");
File file = fileChooser.showSaveDialog(primaryStage);
if(file != null)
{
try {
ImageIO.write(SwingFXUtils.fromFXImage(image, null), "png", file);
}
catch (IOException e) {
System.out.println("Couldn't Save.");
}
}
}
});
But my compiler NetBeans IDE 8.1 is giving an error:
incompatible types: SnapshotParameters cannot be converted to Callback<SnapshotResult, Void>
Can someone tell me what I am doing wrong?

And your compiler is right. A Scene just does not have a method like the one you are trying to call. Just use
WritableImage image = scene.snapshot(null);

Related

How can i make JavaFX filechooser alwaysonTop of window?

How can i make JavaFX filechooser is always on top?
In my application some other dialogs call filechooser and that dialog is set as alwaysonTop, so the filechooser dialog is located behind that dialog.
How can i make the filechooser dialog is alwaysonTop of the window?
I made filechooser like this code.
public static File getSaveFileFX(final String suffix, String title) {
File[] selectedFile = {null};
FileChooser fc = new FileChooser();
fc.setTitle(title);
String root = "*" + suffix;
String fileFormat = suffix + " files";
fc.getExtensionFilters().addAll(new ExtensionFilter(fileFormat, root));
fc.setInitialDirectory(new File(getRecentDirectoryPath()));
PlatformImpl.runAndWait(new Runnable() {
#Override
public void run() {
selectedFile[0] = fc.showSaveDialog(null);
if(selectedFile[0] != null && !title.equals("Sava To .CSV file")) {
//filtering with title
mPreferences.put(RECENT_FILE_PATH, selectedFile[0].getAbsolutePath());
mPreferences.put(RECENT_DIRECTORY_PATH, selectedFile[0].getParent());
}
}
});
if(selectedFile[0] != null && !selectedFile[0].getName().endsWith(suffix)) {
return new File(selectedFile[0].getAbsolutePath()+"."+suffix);
}else {
return selectedFile[0];
}
}
and the other dialog is set as
dialog.alwaysOnTop(true);
You have to set main dialog alwaysOnTop(false);
And the dialog of FileChooser alwaysOnTop(true);
Check this sample, its work.
public void initializationDialog(Stage stage) {
stage.resizableProperty().setValue(false);
stage.setAlwaysOnTop(false);
stage.toBack();
openFile();
}
public File openFile(String descriptionOfFile, String extensionOfFile) {
FileChooser fileChooser = new FileChooser();
Stage stage2 = new Stage();
stage2.initOwner(stage);
stage2.initModality(Modality.WINDOW_MODAL);
stage2.setAlwaysOnTop(true);
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(descriptionOfFile, extensionOfFile);
fileChooser.getExtensionFilters().add(filter);
return fileChooser.showOpenDialog(stage2);
}

why javafx mediaplayer status sometimes returns unknown?

First i am sorry for my poor english...
i made Media Player Application with Javafx.
this player can get mulit file media. and play files out of all limits.
it work well. but sometimes not work..
it is not media error. it is mediaplayer error.
error message is 'mediaPlayer Unknown, media Invalid..' why.??
i played same video file(1920 * 1080), sometimes work and sometimes not work..
and javafx is depend on OS ??
player works perfectly on windown7 computer
but player have this error on windown10 computer...
please give me advice..
MediaPlayer mediaPlayer = null;
Stage stage = new Stage();
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
MediaView mediaView = new MediaView();
int mNextFileIndex = -1;
List<File> fileLists = new ArrayList<>();
Media media;
mediaplayer play Method
public void playNextMedia() {
if (mediaPlayer != null) {
mediaPlayer.dispose();
mediaView.setMediaPlayer(null);
}
mNextFileIndex = (mNextFileIndex + 1) % fileLists.size();
media =new Media(fileLists.get(mNextFileIndex).toURI().toString());
media.setOnError(()-> {
MainApp.makeLog("media error");
});
mediaPlayer = new MediaPlayer(media);
mediaView.setMediaPlayer(mediaPlayer);
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
});
mediaPlayer.setOnEndOfMedia(() -> {
playNextMedia();
});
mediaPlayer.setOnError(() -> {
systom.out.println("mediaPlayer error");
Systeom.out.println(mediaPlayer.getError().getMessage());
playNextMedia();
});
}
Button Method
#FXML
private void playMedia(ActionEvent event) {
mNextFileIndex = -1;
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(new
FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4"),
new FileChooser.ExtensionFilter("All Files", "*.*"));
List<File> list = fileChooser.showOpenMultipleDialog(null);
if (list != null) {
for (File file : list) {
fileLists.add(file)
}
playNextMedia();
pane.getChildren().add(mediaView);
stage.setScene(scene);
stage.show();
}

How to add a set as wallpaper button

Hello everyone I am creating an online wallpaper app.Where users can access wallpaper online.i want add two button first one is set as wallpaper and second one is download button .So if anybody help me about this I will be thankful to them thanks.
public class GalleryDetailActivity extends ActionBarActivity {
public static final String EXTRA_IMAGE = "extra_image";
private ImageView mImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_detail);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mImageView = (ImageView) findViewById(R.id.image);
if (getIntent() != null && getIntent().getExtras() != null) {
if (getIntent().getExtras().containsKey(EXTRA_IMAGE)) {
Picasso.with(this).load(getIntent().getExtras().getString(EXTRA_IMAGE)).into(mImageView);
}
}
First of all, you should make sure you have permission to make such action. Add in your manifest:
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
To download the image hosted in some site you could use a 'doInBackground Thread' as suggested below:
How to download and save an image in Android
The button to set the wallpaper is created by code below:
Button setWallpaper = (Button)findViewById(R.id.YOUR_BUTTON);
ImageView imagePreview = (ImageView)findViewById(R.id.YOUR_PREVIEW);
imagePreview.setImageResource(YOUR_IMAGE_RESOURCE);
setWallpaper.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(YOUR_IMAGE_RESOURCE);
} catch (IOException e) {
e.printStackTrace();
}
}});
YOUR_IMAGE could be a local resource, like:
R.drawable.myImageFile
The link in the answer there are several ways of how to download your online image. Please, check it and try set up your wallpaper with local images first.
File f = new File(Environment.getExternalStorageDirectory(), "yourfile.jpg");
String path = f.getAbsolutePath();
File jpg = new File(path);
if(jpg.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(path);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
WallpaperManager m=WallpaperManager.getInstance(this);
try {
m.setBitmap(bmp);
} catch (IOException e) {
e.printStackTrace();
}
}

How to close javafx and swing window threads between subsequent calls?

Below is a functioning class that simulates extracting data from a website. The question is how to close the window and threads after the data is retrieved? The error message is
Exception in thread "AWT-EventQueue-0" java.lang.IllegalStateException: Platform.exit has been called
On line: final JFXPanel fxPanel = new JFXPanel() {
Here is the code. When Platform.exit() is inserted at the indicated locations, the above error occurs. In the actual code, javafx is used for obtaining and scanning the html text. Also, javafx is used for setting attributes on the server and starting a program on the server, both done using java script. The javafx functionality was removed from this minimal example that demonstrates the error that occurs when using Platform.exit().
public class Step11a {
public static void main(String[] args) throws ParseException, InterruptedException {
Step11a st = new Step11a();
st.getData();
st.getData();
}
private JTable table;
private String url;
private WebView webView;
public Step11a() {
url = "https://www.tsp.gov/investmentfunds/shareprice/sharePriceHistory.shtml";
table = new JTable();
}
private Scene createScene(ArrayBlockingQueue<DefaultTableModel> platfromQueue) {
StackPane root = new StackPane();
Scene scene = new Scene(root);
webView = new WebView();
WebEngine webEngine = webView.getEngine();
Worker<Void> worker = webEngine.getLoadWorker();
worker.stateProperty().addListener((Observable o) -> {
if (worker.getState() == Worker.State.SUCCEEDED) {
DefaultTableModel tableDataModel = (DefaultTableModel) table.getModel();
// Following steps deleted for minimal example
// 1) Get html code from server
// 2) Locate elements to modify
// 3) Create javascript string to modify element values
// 4) Execute javascript to update elemetns
// 5) Execute javascript to start data retrieval on server
// 6) Get html and extract table of data
// For this example, we just set the rows and columns
// in the table
tableDataModel.setColumnCount(11);
tableDataModel.setRowCount(24);;
try {
platfromQueue.put(tableDataModel);
} catch (Exception e) {
e.printStackTrace();
}
}
});
webEngine.load(url);
root.getChildren().add(webView);
return scene;
}
private DefaultTableModel initAndShowGUI() { // This method is invoked on the EDT thread
JFrame frame = new JFrame("WebViewTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JFXPanel fxPanel = new JFXPanel() {
private static final long serialVersionUID = 1L;
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 400);
}
};
frame.add(fxPanel, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
ArrayBlockingQueue<DefaultTableModel> platformQueue = new ArrayBlockingQueue<DefaultTableModel>(5) ;
Platform.runLater(() -> {
initFX(fxPanel,platformQueue);
});
DefaultTableModel tspData = null;
try {
tspData = platformQueue.take();
} catch (Exception e) {
e.printStackTrace();
}
// Platform.exit(); // At this location causes error on next call
// error occurs on final JFXPanel fxPanel = new JFXPanel() {
return tspData;
}
private void initFX(JFXPanel fxPanel, ArrayBlockingQueue<DefaultTableModel> platformQueue) {
// This method is invoked on the JavaFX thread
// System.out.println("JavaFx thread name "+Thread.currentThread().getName());
Scene scene = createScene(platformQueue);
fxPanel.setScene(scene);
}
private DefaultTableModel getData() {
ArrayBlockingQueue<DefaultTableModel> swingQueue = new ArrayBlockingQueue<>(5);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
DefaultTableModel tspDataLocal = initAndShowGUI( );
swingQueue.put(tspDataLocal);
} catch (java.lang.ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
DefaultTableModel tableJFrameData = null;
try {
tableJFrameData = swingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
// Platform.exit(); // At this location causes error on next call
// error occurs on final JFXPanel fxPanel = new JFXPanel() {
return tableJFrameData;
}
}

Deleting a file(s) through FileChooser?

I have a JavaFX app using JRE1.8.0 u40. I converted my Swing JFileChooser Open and Save to the newer JavaFX FileChooser Open and Save, Windows7 style Dialog box. But I have not found an equivalent JavaFX FileChooser method to replace the JFileChooser method I'm using for deleting a file(s) as shown below:
public static void deleteFile() throws IOException {
JFileChooser fileDialog = new JFileChooser("C:\\ProgramData\\L1 Art Files\\");
File[] selectedFiles;
fileDialog.setSelectedFiles(null);
// Set frame properties
fileDialog.setDialogTitle("Delete Pixel Art File(s)");
//fileDialog.setLayout(new FlowLayout());
fileDialog.setSize(400, 400);
fileDialog.setVisible(true);
fileDialog.setMultiSelectionEnabled(true); // Allow multiple selection
fileDialog.setVisible(true);
int option = fileDialog.showDialog(null, "Delete");
if (option != JFileChooser.APPROVE_OPTION)
return; //user canceled the
selectedFiles = fileDialog.getSelectedFiles();
if (selectedFiles != null) { //ask the user to replace this file
int response = JOptionPane.showConfirmDialog(null, "Are you sure want to delete this file?",
"Confirm Delete",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE);
if (response != JOptionPane.YES_OPTION) return;
}
for (File f : selectedFiles) {
Files.delete(f.toPath());
}
Is there a similar solution to the above for JavaFX using FileChooser or do I use the showOpenDialog(null) with setTitle("Delete Pixel Art File")?
You can easily perform that task using javafx like below :
#FXML
private void onDeleteAction(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Your_title_here");
List<File> selectedFiles = fileChooser.showOpenMultipleDialog(null);
if (selectedFiles != null) {
Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
alert.setTitle("Confirmation Dialog");
alert.setHeaderText("Warning !");
alert.setContentText("Are you sure you want to delete these files ?");
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
for (File selectedFile : selectedFiles) {
selectedFile.delete();
}
}
} else {
System.out.println("Error Selection");
}
}
The above code was very helpful and works best with the other suggestion of checking for null and adding throws IOException to the deleteFile() method.

Resources