Image didn't load in JPanel - java

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.

You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.

Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

Related

Saving images using dialogs in java FXML (java 8)

So im trying to save a image (Image class from javafx.scene.image.Image) onto a file with a save file dialog (JFileChooser) so that it is user friendly.
What i want it to do: Save the image specified
What it does: Save dialog works (i think), and it doesn't save (write to file) anything.
Here is the code behind it:
public void saveFile() { //menu item interface for save and save as
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Save");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
//Setting the file extentions
/*fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Image", ".png"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG Image", ".jpg"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP Image", ".bmp"));*/
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile(); //selected file
saveToFile(picFrame.getImage(), fileToSave); //save the file
System.out.println("Save as file: " + fileToSave.getAbsolutePath()); //debug because it doesnt work
}
parentFrame.dispose();
}
and here is saveToFile
public static void saveToFile(Image image, File file) {
String extension = "";
File outputFile = file;
try {
if (file != null && file.exists()) {
String name = file.getName();
extension = name.substring(name.lastIndexOf("."));
}
} catch (Exception e) {
extension = "";
}
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
try {
ImageIO.write(bImage, extension, outputFile);
System.out.println("Saveing file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
After some digging arround and debuging i found the problem and the solution , so here it is.
All the code.
public void saveFile() { //menu item interface for save and save as
Window mainStage = ap.getScene().getWindow(); //get ze window
FileChooser fileChooser = new FileChooser(); //Filechooser the class that has the file chooser
fileChooser.setTitle("Open Resource File"); //Title of prompt
fileChooser.getExtensionFilters().addAll( //add filter
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif", ".bmp"), //Filters
new ExtensionFilter("All Files", "*.*")); //Filters
File selectedFile = fileChooser.showSaveDialog(mainStage); //get the file
if (selectedFile != null) { //if something is selected then
System.out.println(selectedFile.getAbsoluteFile()); //debug
System.out.println(selectedFile.getAbsoluteFile().getParent()); //debug
Image img = SwingFXUtils.toFXImage(bImg, null); //convert to Image
saveToFile(img, selectedFile); //save the Image
}
}
/**
* A simple image save
*
* #param image The image you want to save
* #param file The file where you want to save it
*/
public static void saveToFile(Image image, File file) {
File outputFile = file; //file
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); //Convert to bufferedimage
try {
ImageIO.write(bImage, getFileExtension(outputFile).toUpperCase(), outputFile.getAbsoluteFile()); //actualy save
System.out.println("Saveing file ex: " + getFileExtension(outputFile).toUpperCase() + " to: " + outputFile.getAbsoluteFile() + " with name " + outputFile.getName());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".") + 1;
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}

How can I fix my code so that it contains both a "save" and "save as" functions?

I have two buttons in a menubar that contains both a save and save as button. However, I currently have the code for both of them the same and it does the save as currently with prompting the user where they want to save. I want the save button to only save without prompting for the dialog unless the file doesn't yet exist.
I've tried fiddling around with the code to try and figure out a workaround, but have not figure it out.
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
});
The code currently does the exact same save function for each save button. I want it to only prompt for the save as button.
You need to have a File instance field in your class that is initially assigned to null. When you read in a File or when you do your first save, then this field is assigned to that File. When the save button is pressed, then you check if the field is null, and if so, show the dialog as you would for the save-as button. If the field is not null, then you simply write the file to disk using the data that you have and that File.
for example (code not tested):
// a private instance field
private File myFile = null;
fileMenu.getItems().add(saveItem);
saveItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
if (myFile == null) {
saveAs();
} else {
writeFile(myFile);
}
}
});
fileMenu.getItems().add(saveAsItem);
saveAsItem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
saveAs();
}
});
private void writeFile(File file) {
if (file != null) {
try {
WritableImage writableImage = new WritableImage(width, height);
canvas.snapshot(null, writableImage);
RenderedImage renderedImage = SwingFXUtils.fromFXImage(writableImage, null);
ImageIO.write(renderedImage, "png", file);
} catch (IOException ex) {
System.out.println("Error");
}
}
}
private void saveAs() {
FileChooser saveFile = new FileChooser();
saveFile.getExtensionFilters().add(new FileChooser.ExtensionFilter("Image Files", "*.png", "*.jpg"));
saveFile.setTitle("Save File");
File file = saveFile.showSaveDialog(stage);
myFile = file; // !!
writeFile(file);
}

Java implementing a FileOpener

So am trying to make a button where it opens a FileChoser to import an image .
My probleme is :
1-I want the fileChoser to display only images-files(.jpg ...).
2-When the FileOpener opens , the other windows should be Disabled until the
FileOpener is disposed . In my case , they are disabled but when I click on them my programe crashes for some reason .
3-If there is a better FileOpener it will be welcomed , this si not mine I found it on the net .
Here's my source code :
public class FileOpener {
private JFileChooser file_chooser = new JFileChooser();
StringBuilder path = new StringBuilder();
public File choosed() {
File file = null;
if(file_chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
file = file_chooser.getSelectedFile();
Scanner input = null;
try {
input = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Fail");
e.printStackTrace();;
}
while(input.hasNext()) {
path.append(input.nextLine());
}
input.close();
}
return file;
}
public String getPath() {
return path.toString();
}
}
And here's my call (Where there is a probleme is the enable-disable window) :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
shell.setEnabled(false);
FileOpener v = new FileOpener();
File file = v.choosed();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
shell.setEnabled(true);
}
});
Notice that this code works , but am trying just to fix the bugs,the "ScaleImage" fonction reScale the chosen Image to fit my label.
I managed to fix the Enable-disable problem simply by removing all what was interfering with the shell :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileOpener v = new FileOpener();
File file = v.choosed();
shell.forceActive();
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
I fixed completly my probleme by using FileDialog :
Button button_2 = new Button(composite_1, SWT.FLAT);
button_2.addSelectionListener(new SelectionAdapter() {
#Override
public void widgetSelected(SelectionEvent e) {
FileDialog test = new FileDialog(shell);
test.open();
File file = new File(test.getFilterPath()+"\\"+test.getFileName());
if(file != null) {
Image image = new Image(shell.getDisplay(), file.getPath());
Image image2 = main.ScaleImage(image, Image_input);
Image_input.setImage(image2);
}
}
});
Thanks for greg-449 for the answer .I didn't know how to exactly work with the new GUI but to get the file path :
test.getFilterPath()+"\\"+test.getFileName()

Java JNA- Jar application hangs in 32 bit windows system

Here's a screenshot application. Compiled with 1.8 JDK, works perfectly well in 64 bit systems, but lags and hangs in two iterations in 32 bit systems.
Basically this application takes a screenshot using robot class, takes the file name from user which is a URL. Truncates and removes all illegal characters from it and saves it using a save as dialog box with time-stamp as the prefix.
I am using Windows Low Level KeyHook to initiate the screenshot with PrtSc key.
Error in 32 bit systems:
It only takes 2 screenshots and then does not respond when I press PrtSc for the 3rd time. Can JFrame cause any problems, it certainly loads up slow. Should I use any alternate text box than JFrame or is it because I have complied in java 1.8 jdk 64 bit environment, which wont work in lower versions of jdk or 32 bit systems.
public class KeyHook {
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
static JFileChooser fileChooser = new JFileChooser();
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch(wParam.intValue()) {
case WinUser.WM_KEYUP:
case WinUser.WM_KEYDOWN:
case WinUser.WM_SYSKEYUP:
case WinUser.WM_SYSKEYDOWN:
if (info.vkCode == 44) {
try {
Robot robot = new Robot();
// Capture the screen shot of the area of the screen defined by the rectangle
BufferedImage bi=robot.createScreenCapture(new Rectangle(0,25,1366,744));
JFrame frame = new JFrame();
JFrame.setDefaultLookAndFeelDecorated(true);
frame.toFront();
frame.requestFocus();
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// prompt the user to enter their name
String name = JOptionPane.showInputDialog(frame, "Enter file name");
// frame.pack();
frame.dispose();
String fileName= dovalidateFile(name);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PNG", ".png");
fileChooser.setFileFilter(filter);
fileChooser.setSelectedFile(new File (fileName));
int returnVal = fileChooser.showSaveDialog(null);
if ( returnVal == JFileChooser.APPROVE_OPTION ){
File file = fileChooser.getSelectedFile();
file = validateFile(file);
System.out.println(file);
ImageIO.write(bi, "png", file);
}
}
catch (NullPointerException e1)
{e1.printStackTrace(); }
catch (AWTException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
private File validateFile(File file) {
DateFormat dateFormat = new SimpleDateFormat("HH.mm.ss.ddMMMMMyyyy");
//get current date time with Calendar()
Calendar cal = Calendar.getInstance();
// System.out.println(dateFormat.format(cal.getTime()));
String filePath = file.getAbsolutePath();
if (filePath.indexOf(".png") == -1) {
filePath += "." + dateFormat.format(cal.getTime()) + ".png";
}
//System.out.println("File Path :" + filePath);
file = new File(filePath);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
private String dovalidateFile(String name) {
String input = name.replace("https://www.","");
input = input.replaceAll("http://www.","");
input = input.replaceAll("https://","");
input = input.replace("http://","");
input = input.replace("/?",".");
input = input.replace("/",".");
input = input.replace("|",".") ;
input = input.replace("%",".");
input = input.replace("<",".");
input = input.replace(">",".");
input = input.replaceAll("\\?",".");
input = input.replaceAll("\\*",".");
input = input.replace(":",".");
input = input.replace("\\",".");
input = Character.toUpperCase(input.charAt(0)) + input.substring(1);
return input;
}
};
hhk = lib.SetWindowsHookEx(WinUser.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
if(!SystemTray.isSupported()){
return ;
}
SystemTray systemTray = SystemTray.getSystemTray();
Image image = Toolkit.getDefaultToolkit().getImage(KeyHook.class.getResource("/images/icon.png"));
//popupmenu
PopupMenu trayPopupMenu = new PopupMenu();
MenuItem close = new MenuItem("Exit");
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
});
trayPopupMenu.add(close);
//setting tray icon
TrayIcon trayIcon = new TrayIcon(image, "captur", trayPopupMenu);
//adjust to default size as per system recommendation
trayIcon.setImageAutoSize(true);
try{
systemTray.add(trayIcon);
}catch(AWTException awtException){
awtException.printStackTrace();
}
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
}
else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
lib.UnhookWindowsHookEx(hhk);
}
}
I don't have any experience with JNA, but there are several things that are wrong about your code - I don't think I got them all, but here are some:
close.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
quit=true;
}
});
The quit=true will never be reached because your program exit()s before it ever goes there.
2.
new Thread() {
public void run() {
while (!quit) {
try { Thread.sleep(10); } catch(Exception e) { }
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
doesn't make any sense since quit will never be true. Also spinning on a variable to detect a change will severly slow down your application (espacially with sleep-times of 10 ms). Why not do the unhook in your ActionListener?
3.
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
Here I'm not too sure because I don't have experience with JNA and the windows event system. The method waits for messages sent to the specified window, but since you don't specify any (second parameter is null) I don't think you will ever get one.
For each callback you are creating a new JFrame but at the end of the method you are only hiding it using frame.setVisible(false);. Since it is still referenced from various Swing-classes it will never be garbage-collected. This creates a memory-leak which will slow down your application. You will have to call frame.dispose() to get rid of it.

how to upload and display image in JFrame using JFileChooser

I need to upload and display an image selected with the JFileChooser (i.e the user wants to set his/her profile picture) in a JFrame.. How should I do it?
Here is my code for choosing the file:
private void UploadImageActionPerformed(java.awt.event.ActionEvent evt) {
int returnVal = fileChosser.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChosser.getSelectedFile();
// What to do with the file
// I want code for this part
try {
//code that might create an exception
}
catch (Exception e1) {
e.printStackTrace();
}
}
}
I solved it myself. I chose an image and displayed in a JLabel.
Here is My code:
private void uploadImageActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser filechooser = new JFileChooser();
filechooser.setDialogTitle("Choose Your File");
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
// below code selects the file
int returnval = filechooser.showOpenDialog(this);
if (returnval == JFileChooser.APPROVE_OPTION)
{
File file = filechooser.getSelectedFile();
BufferedImage bi;
try {
// display the image in a Jlabel
bi = ImageIO.read(file);
jLabel1.setIcon(new ImageIcon(bi));
} catch(IOException e) {
e.printStackTrace(); // todo: implement proper error handeling
}
this.pack();
}
}

Categories