importing error with import javax.imageio.ImageIO; - javax.imageio

I am new to Java and are trying to display an image. I got code on the net but when trying it I get an error with the importing of " import javax.imageio.ImageIO;" The error message reads "javax.imageio.ImageIO" is either a misplace package name or a non-existing entity.
I have seen this on many samples but it does not work with me.
Is there any advice
mport java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Showmap extends Panel
{
BufferedImage img;
public Showmap ()
{
try
{
image = ImageIO.read (new File ("KNP.jpg"));
}
/*
catch (IOException e)
{
BufferedImage image;
public ShowImage() {
try {
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
image = ImageIO.read(input);
}*/
catch (IOException e)
{
System.out.println ("Error:" + e.getMessage ());
}
}
public void paint (Graphics g)
{
g.drawImage (image, 0, 0, null);
}
static public void main (String args []) throws
Exception
{
JFrame frame = new JFrame ("Display image");
Panel panel = new Showmap ();
frame.getContentPane ().add (panel);
frame.setSize (500, 500);
frame.setVisible (true);
}
}
Thanks
Ivan

In your Project select:
Right Click on "JRE System Libary"
Select Properties
On Execution Enviroment select "J2SE-1.5(jre8)" or later; you should use the latest version of jre8

I was programming with "Ready to Program" and tried many options with out success. When I copied the same code to "JCreator" and run it fro there it was working fine. Seems "import javax.imageio.ImageIO;" is not working with "Ready to Program".

Related

Write JavaFX Blob data field image

In my class, the attribute where the image will be saved is defined like this:
#Lob
#Column(name = "NOTA_FISCAL", nullable = false, columnDefinition = "mediumblob")
public byte[] getNOTA_FISCAL() {
return NOTA_FISCAL;
}
public void setNOTA_FISCAL(byte[] NOTA_FISCAL) {
this.NOTA_FISCAL = NOTA_FISCAL;
}
In a project I made using Swing, I used JFileChooser to read an image from my computer to later insert it into the database, we can see that the file is converted to Bytes before inserting the item.
private void selecionarNF(ActionEvent event) {
JFileChooser fc = new JFileChooser();
int res = fc.showOpenDialog(null);
if (res == JFileChooser.APPROVE_OPTION) {
File arquivo = fc.getSelectedFile();
System.out.println("Arquivo: " + arquivo + "");
textCaminhoNF.setText(String.valueOf(arquivo));
try {
byte[] fotonf = new byte[(int) arquivo.length()];
FileInputStream fileInputfotonf = new FileInputStream(arquivo);
fileInputfotonf.read(fotonf);
fileInputfotonf.close();
fotoNF = fotonf;
} catch (Exception ex) {
// System.out.println(ex.printStackTrace().toString());
}
} else {
JOptionPane.showMessageDialog(null, "VocĂȘ nao selecionou nenhum arquivo.");
}
I'm implementing it with JavaFX, I could even continue using Swing, but I intend to use the Windows file explorer, this way using FileChooser, however I'm having problems capturing the image and passing it to an object of type File, the . getSelectedFile() doesn't exist for FileChooser, I searched a lot on the internet and couldn't find a way to capture this file. What would be the correct way?
Stage s = new Stage();
FileChooser fc = new FileChooser();
textCaminhoNF.setText(fc.showOpenDialog(s).getAbsolutePath());
File arquivo = fc.getSelectedFile(); //his line shows the error, because there is no .getSelectItem
if (fc != null) {
System.out.println("No is null");
try
{
byte[] fotonf = new byte[(int) fc.length()];
FileInputStream fileInputfotonf = new FileInputStream(fc);
fileInputfotonf.read(fotonf);
fileInputfotonf.close();
fotoNF = fotonf;
} catch (Exception ex) {
// System.out.println(ex.printStackTrace().toString());
}
}
I agree with what #slaw has mentioned. You are not saving the file reference returned from showOpenDialog.
Below is a quick demo [from my archives ;-) ] when I tried to check the behavior of FileChooser:
import javafx.application.Application;
import javafx.embed.swing.SwingFXUtils;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class ChooseImage_Demo extends Application {
ImageView myImageView;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button button = new Button("Search for Image");
button.setOnAction(e -> {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
} catch (IOException ex) {
ex.printStackTrace();
}
});
myImageView = new ImageView();
myImageView.setFitWidth(500);
myImageView.setPreserveRatio(true);
VBox vBox = new VBox(10);
vBox.getChildren().addAll(button, myImageView);
vBox.setAlignment(Pos.TOP_CENTER);
Scene scene = new Scene(vBox, 800, 800);
primaryStage.setTitle("Image Chooser");
primaryStage.setScene(scene);
primaryStage.show();
}
}
Thanks for the help, I did it this way and it worked, it's writing correctly to the database too.
#FXML
private void selecionarNF(ActionEvent event) {
ImageView myImageView = null;
myImageView = new ImageView();
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
try {
BufferedImage bufferedImage = ImageIO.read(file);
Image image = SwingFXUtils.toFXImage(bufferedImage, null);
myImageView.setImage(image);
imageToByte(String.valueOf(file));
} catch (IOException ex) {
ex.printStackTrace();
}
textCaminhoNF.setText(String.valueOf(file));
}

Restarting and pausing and resuming clip hangs the gui of music player, while pressing pause and play resumes playing from stopping point

This program is a music player that allows user to pick a .wav file, play, pause, resume, and restart a the music file from a clip object and audioinput stream. The audio input stream loads a file that is determined by user via FileChooser. The program can play, pause, and resume by selecting a file, pressing play, pause, then play again, but does not play using the restart method or the resume method invoked via the respective buttons. Instead, the program hangs until the X button is clicked. I think it has something to do with the resetaudiostream method, but I am unsure what. Maybe something to do with ending the old clip and creating a new clip instance. Please review the logic and let me know what is making it hang and how that could be remedied.
package sample;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;
public class Main extends Application {
static File musicfile;
static Long currentFrame;
static Clip clip;
static String status = "play";
static AudioInputStream audioInputStream;
static String filePath;
public void SimpleAudioPlayer()
throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
// create AudioInputStream object
audioInputStream =
AudioSystem.getAudioInputStream(new File(filePath).getAbsoluteFile());
// create clip reference
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
#Override
public void start(Stage primaryStage) throws Exception{
Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
primaryStage.setTitle("Music Player");
GridPane gp = new GridPane();
Button selectFile = new Button("Select File");
GridPane.setConstraints(selectFile, 0,0);
selectFile.setOnAction(event->{
FileChooser filechooser = new FileChooser();
// create AudioInputStream object
try {
musicfile = filechooser.showOpenDialog(null);
audioInputStream = AudioSystem.getAudioInputStream(musicfile);
clip = AudioSystem.getClip();
// open audioInputStream to the clip
clip.open(audioInputStream);
}catch(IOException | UnsupportedAudioFileException | LineUnavailableException e){
e.printStackTrace();
}
});
Button play = new Button("Play");
GridPane.setConstraints(play, 1,0);
play.setOnAction(event->{
if(status == "play") {
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
play();
});
Button pause = new Button("Pause");
GridPane.setConstraints(pause, 2,0);
pause.setOnAction(event -> pause());
Button restart = new Button("Restart");
GridPane.setConstraints(restart, 0,1);
restart.setOnAction(event -> {
try{
restart();
}
catch(IOException | UnsupportedAudioFileException | LineUnavailableException e){
e.printStackTrace();}
});
Button resume = new Button("Resume");
GridPane.setConstraints(resume, 1,1);
resume.setOnAction(event -> {
try {
resumeAudio();
}catch(IOException | LineUnavailableException | UnsupportedAudioFileException e){
e.printStackTrace();
}
});
gp.getChildren().addAll(play,selectFile, pause, restart, resume);
primaryStage.setScene(new Scene(gp, 300, 275));
primaryStage.show();
}
public void play()
{
//start the clip
clip.start();
status = "play";
}
// Method to pause the audio
public void pause()
{
if (status.equals("paused"))
{
System.out.println("audio is already paused");
return;
}
currentFrame =
clip.getMicrosecondPosition();
clip.stop();
status = "paused";
}
// Method to resume the audio
public void resumeAudio() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
if (status.equals("play"))
{
System.out.println("Audio is already "+
"being played");
return;
}
clip.close();
resetAudioStream();
clip.setMicrosecondPosition(currentFrame);
status = "play";
play();
}
// Method to restart the audio
public void restart() throws IOException, LineUnavailableException,
UnsupportedAudioFileException
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = 0L;
clip.setMicrosecondPosition(0);
status = "play";
play();
}
// Method to stop the audio
public void stop() throws UnsupportedAudioFileException,
IOException, LineUnavailableException
{
currentFrame = 0L;
clip.stop();
clip.close();
}
// Method to jump over a specific part
public void jump(long c) throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
if (c > 0 && c < clip.getMicrosecondLength())
{
clip.stop();
clip.close();
resetAudioStream();
currentFrame = c;
clip.setMicrosecondPosition(c);
this.play();
}
}
// Method to reset audio stream
public void resetAudioStream() throws UnsupportedAudioFileException, IOException,
LineUnavailableException
{
audioInputStream = AudioSystem.getAudioInputStream(musicfile);
clip = AudioSystem.getClip();
clip.open(audioInputStream);
clip.loop(Clip.LOOP_CONTINUOUSLY);
}
public static void main(String[] args) {
launch(args);
}
}
It is quiet simple to get the required functionality with a MediaPlayer:
import java.net.URI;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.stage.Stage;
import javafx.util.Duration;
/*
* If you get "cannot access class com.sun.glass.utils.NativeLibLoader" exception you may need to
* add a VM argument: --add-modules javafx.controls,javafx.media as explained here:
* https://stackoverflow.com/questions/53237287/module-error-when-running-javafx-media-application
*/
public class Main extends Application {
private MediaPlayer player;
private static final long JUMP_BY = 5000;//millis
#Override
public void start(Stage primaryStage) throws Exception{
URI uri = new URI("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3");
Media media = new Media(uri.toString());
//OR Media media = new Media("https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3");
player = new MediaPlayer(media);
player.setOnError(() -> System.out.println(media.getError().toString()));
GridPane gp = new GridPane();
gp.setHgap(10);
Button play = new Button("Play");
GridPane.setConstraints(play, 0,0);
play.setOnAction(event-> playAudio());
Button pause = new Button("Pause");
GridPane.setConstraints(pause, 1,0);
pause.setOnAction(event -> pauseAudio());
Button resume = new Button("Resume");
GridPane.setConstraints(resume, 2,0);
resume.setOnAction(event -> resumeAudio());
Button stop = new Button("Stop");
GridPane.setConstraints(stop, 3,0);
stop.setOnAction(event -> stopAudio());
Button restart = new Button("Restart");
GridPane.setConstraints(restart, 4,0);
restart.setOnAction(event -> restartAudio());
Button jump = new Button("Jump >");
GridPane.setConstraints(jump, 5,0);
jump.setOnAction(event -> jump(JUMP_BY));
Label time = new Label();
GridPane.setConstraints(time, 6,0);
time.textProperty().bind( player.currentTimeProperty().asString("%.4s") );
gp.getChildren().addAll(play, pause, resume, stop, restart, jump, time);
primaryStage.setScene(new Scene(gp, 400, 45));
primaryStage.show();
}
//play audio
public void playAudio()
{
player.play();
}
//pause audio
public void pauseAudio()
{
if (player.getStatus().equals(Status.PAUSED))
{
System.out.println("audio is already paused");
return;
}
player.pause();
}
//resume audio
public void resumeAudio()
{
if (player.getStatus().equals(Status.PLAYING))
{
System.out.println("Audio is already playing");
return;
}
playAudio();
}
//restart audio
public void restartAudio()
{
player.seek(Duration.ZERO);
playAudio();
}
// stop audio
public void stopAudio()
{
player.stop();
}
//jump by c millis
public void jump(long c)
{
player.seek(player.getCurrentTime().add(Duration.millis(c)));
}
public static void main(String[] args) {
launch(args);
}
}

jxbrowser -- jquery.AreYouSure .. warning message always in English...

i trying to use jquery.AreYouSure into JxBrowser(5.2 and/or next version).
jquery.AreYouSure works... but the warning pop up windows is always in english...
This behaviour is wrong and differ from chrome/firox/ie.... these show message in the current language...
this is a demo url
http://www.papercut.com/products/free-software/are-you-sure/demo/are-you-sure-demo.html
By default, JxBrowser displays dialogs configured with English language. At the same time, JxBrowser API provides functionality that allows modifying default behavior and display your own dialogs with required language. To change the language you need to register your own DialogHandler where you can display your own dialog. For example:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.CloseStatus;
import com.teamdev.jxbrowser.chromium.UnloadDialogParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultDialogHandler;
import javax.swing.*;
import java.awt.*;
/**
* The sample demonstrates how to catch onbeforeunload dialog.
*/
public class BeforeUnloadSample {
public static void main(String[] args) {
Browser browser = new Browser();
final BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setVisible(true);
browser.setDialogHandler(new DefaultDialogHandler(view) {
#Override
public CloseStatus onBeforeUnload(UnloadDialogParams params) {
String title = "Confirm Navigation";
String message = params.getMessage();
int returnValue = JOptionPane.showConfirmDialog(view, message, title, JOptionPane.OK_CANCEL_OPTION);
if (returnValue == JOptionPane.OK_OPTION) {
return CloseStatus.OK;
} else {
return CloseStatus.CANCEL;
}
}
});
browser.loadHTML("<html><body onbeforeunload='return myFunction()'>" +
"<a href='http://www.google.com'>Click here to leave</a>" +
"<script>function myFunction() { return 'Leave this web page?'; }" +
"</script></body></html>");
}
}

How do you close a JOGL/NEWT GLWindow completely?

I have an incredibly dumb little sample, probably ripped straight from a tutorial, every time it runs it generates warnings on exit. I'm curious what I'm missing. Any ideas, links, things I'm forgetting?
Here's the main window setup...
package com.emarcotte;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import com.jogamp.newt.event.KeyAdapter;
import com.jogamp.newt.event.KeyEvent;
import com.jogamp.newt.event.WindowAdapter;
import com.jogamp.newt.event.WindowEvent;
import com.jogamp.newt.opengl.GLWindow;
import com.jogamp.opengl.util.FPSAnimator;
public class Main2 {
public static void main(String[] args) {
final RenderLoop loop = new RenderLoop();
GLProfile glp = GLProfile.get(new String[] { GLProfile.GL3 }, true);
GLCapabilities caps = new GLCapabilities(glp);
GLWindow window = GLWindow.create(caps);
window.setSize(300, 300);
window.setVisible(true);
window.setTitle("NEWT Window Test");
window.addGLEventListener(loop);
window.setAnimator(new FPSAnimator(window, 120));
window.getAnimator().start();
window.addWindowListener(new WindowAdapter() {
#Override public void windowResized(WindowEvent we) {
loop.setHeight(window.getHeight());
loop.setWidth(window.getWidth());
}
});
window.addKeyListener(new KeyAdapter() {
#Override public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) {
window.getAnimator().stop();
}
}
});
}
}
here are the warnings:
X11Util.Display: Shutdown (JVM shutdown: true, open (no close attempt): 2/2, reusable (open, marked uncloseable): 0, pending (open in creation order): 2)
X11Util: Open X11 Display Connections: 2
X11Util: Open[0]: NamedX11Display[:0.0, 0x7f214c0012b0, refCount 1, unCloseable false]
X11Util: Open[1]: NamedX11Display[:0.0, 0x7f214c017390, refCount 1, unCloseable false]
Call GLWindow.destroy() to close your NEWT GLWindow: http://jogamp.org/deployment/jogamp-next/javadoc/jogl/javadoc/com/jogamp/newt/opengl/GLWindow.html#destroy%28%29

JavaFX file listview with icon and file name

In a JavaFX dialog, I would like to show a list of files with their icons and file names.
It was easy to find how to get an icon for a file extension:
File file = File.createTempFile("icon", ".doc");
FileSystemView view = FileSystemView.getFileSystemView();
java.swing.Icon icon = view.getSystemIcon(file);
file.delete();
But, how can I draw that Swing Icon in a JavaFX ListView?
private static class AttachmentListCell extends ListCell<String> {
#Override
public void updateItem(String fileName, boolean empty) {
if (item != null) {
// Get file Icon for fileName as shown above.
java.swing.Icon icon =
// Transform Icon to something that can be
// added to the box, maybe an ImageView.
javafx.scene.image.ImageView image = ???
// Label for file name
Label label = new Label(item);
HBox box = new HBox();
box.getChildren().addAll(image, label);
setGraphic(box);
}
}
}
Here is an example for a list view with file icons:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Callback;
import javax.swing.filechooser.FileSystemView;
public class ListViewCellFactory2 extends Application {
ListView<String> list = new ListView<String>();
ObservableList<String> data = FXCollections.observableArrayList(
"a.msg", "a1.msg", "b.txt", "c.pdf",
"d.html", "e.png", "f.zip",
"g.docx", "h.xlsx", "i.pptx");
#Override
public void start(Stage stage) {
VBox box = new VBox();
Scene scene = new Scene(box, 200, 200);
stage.setScene(scene);
stage.setTitle("ListViewSample");
box.getChildren().addAll(list);
VBox.setVgrow(list, Priority.ALWAYS);
list.setItems(data);
list.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> list) {
return new AttachmentListCell();
}
});
stage.show();
}
private static class AttachmentListCell extends ListCell<String> {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setGraphic(null);
setText(null);
} else {
Image fxImage = getFileIcon(item);
ImageView imageView = new ImageView(fxImage);
setGraphic(imageView);
setText(item);
}
}
}
public static void main(String[] args) {
launch(args);
}
static HashMap<String, Image> mapOfFileExtToSmallIcon = new HashMap<String, Image>();
private static String getFileExt(String fname) {
String ext = ".";
int p = fname.lastIndexOf('.');
if (p >= 0) {
ext = fname.substring(p);
}
return ext.toLowerCase();
}
private static javax.swing.Icon getJSwingIconFromFileSystem(File file) {
// Windows {
FileSystemView view = FileSystemView.getFileSystemView();
javax.swing.Icon icon = view.getSystemIcon(file);
// }
// OS X {
//final javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
//javax.swing.Icon icon = fc.getUI().getFileView(fc).getIcon(file);
// }
return icon;
}
private static Image getFileIcon(String fname) {
final String ext = getFileExt(fname);
Image fileIcon = mapOfFileExtToSmallIcon.get(ext);
if (fileIcon == null) {
javax.swing.Icon jswingIcon = null;
File file = new File(fname);
if (file.exists()) {
jswingIcon = getJSwingIconFromFileSystem(file);
}
else {
File tempFile = null;
try {
tempFile = File.createTempFile("icon", ext);
jswingIcon = getJSwingIconFromFileSystem(tempFile);
}
catch (IOException ignored) {
// Cannot create temporary file.
}
finally {
if (tempFile != null) tempFile.delete();
}
}
if (jswingIcon != null) {
fileIcon = jswingIconToImage(jswingIcon);
mapOfFileExtToSmallIcon.put(ext, fileIcon);
}
}
return fileIcon;
}
private static Image jswingIconToImage(javax.swing.Icon jswingIcon) {
BufferedImage bufferedImage = new BufferedImage(jswingIcon.getIconWidth(), jswingIcon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB);
jswingIcon.paintIcon(null, bufferedImage.getGraphics(), 0, 0);
return SwingFXUtils.toFXImage(bufferedImage, null);
}
}
EDIT: On a HDPI monitor, the file icons are clipped.
What has to be done to have the icons entirely displayed in the row?
How can I retrieve the scale factor from Java?
I came up with this code, which seems to work for converting the icon returned by getSystemIcon to a format which JavaFX can understand. It does this by using a combo of SwingUtilities.invokeLater with Platform.runLater to try to mitigate any potential threading issues between the two projects. The javax.swing.Icon is painted to java.awt.BufferedImage which is converted by SwingFXUtils to a JavaFX Image.
So the Swing Icon => JavaFX image portion of the code you were asking about seems to work. The only thing is, when I tested the application on OS X 10.7 running Oracle Java8u20, every file extension type I tried gave the exact same icon. So it would seem that your method for getting an icon from the system via the swing FileSystemView isn't really supported on OS X (as far as I can tell). I guess you could try it on another OS and see if it works for you there (presuming that supporting this icon lookup feature on OS X is not necessary for your task).
So googling around brought up the following question:
Access file type icons Mac OSX
And in that, Sam Barnum recommends a FileView works much better than a FileSystemView - and so it did for me. I switched your code to use a FileView and after that started getting different icons for different file types on OS X. The icons were still really small 16x16 icons (I wouldn't know how to retrieve the hi-res retina icons for instance), but at least the icons which were retrieved appeared correct and file type specific.
import javafx.application.Application;
import javafx.application.Platform;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class FileIconViewer extends Application {
#Override
public void start(Stage stage) throws IOException {
Runnable fetchIcon = () -> {
File file = null;
try {
file = File.createTempFile("icon", ".png");
// commented code always returns the same icon on OS X...
// FileSystemView view = FileSystemView.getFileSystemView();
// javax.swing.Icon icon = view.getSystemIcon(file);
// following code returns different icons for different types on OS X...
final javax.swing.JFileChooser fc = new javax.swing.JFileChooser();
javax.swing.Icon icon = fc.getUI().getFileView(fc).getIcon(file);
BufferedImage bufferedImage = new BufferedImage(
icon.getIconWidth(),
icon.getIconHeight(),
BufferedImage.TYPE_INT_ARGB
);
icon.paintIcon(null, bufferedImage.getGraphics(), 0, 0);
Platform.runLater(() -> {
Image fxImage = SwingFXUtils.toFXImage(
bufferedImage, null
);
ImageView imageView = new ImageView(fxImage);
stage.setScene(
new Scene(
new StackPane(imageView),
200, 200
)
);
stage.show();
});
} catch (IOException e) {
e.printStackTrace();
Platform.exit();
} finally {
if (file != null) {
file.delete();
}
}
};
javax.swing.SwingUtilities.invokeLater(fetchIcon);
}
public static void main(String[] args) { launch(args); }
}
Note: there is an existing request in the JavaFX issue tracker to add this functionality to JavaFX (it is currently not scheduled for implementation, though you could log into the issue tracker and vote for the issue, comment on it, link it back to this StackOverflow question, etc):
RT-19583 Possibility to get native icons, on different sizes.

Resources