0

I have searched on google, looked at the documentation on oracle's webpage, read a chapter about graphics in java but I can't seem to figure it out so please help! I want a button that uploads the image onto a JLabel which is located in a JPanel which is located in a JFrame. Nothing more than that! Why isn't my code working? What happens when I execute the program is absolutely nothing. Nothing gets appended to the log and there aren't any errors... Just nothing that happens, I've been programming java for quite some time now but never worked with graphics so I can't solve the problem by myself...

JLabel imageLabel = new JLabel();
private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {                                             
    JFileChooser fileChooser = new JFileChooser();
    fileChooser.setCurrentDirectory(new java.io.File("C:\\"));
    fileChooser.setDialogTitle("Choose file");
    fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);

    if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        System.out.println("getCurrentDirectory(): "
                + fileChooser.getCurrentDirectory());
        System.out.println("getSelectedFile() : "
                + fileChooser.getSelectedFile());
        imagePath = fileChooser.getSelectedFile().toString();
        ImageIcon imageIcon = new ImageIcon(imagePath);
        imageLabel.setIcon(imageIcon);
    }

}
Darawan
  • 15
  • 8
  • 2
    What happens on execution? Can you provide some error messages? – Hexaholic Apr 26 '15 at 10:32
  • Can you show us the initialization of the label? – Manuel Jain Apr 26 '15 at 10:33
  • Had you tried `imagePath = fileChooser.getSelectedFile().getAbsolutePath();`? – Mordechai Apr 26 '15 at 10:34
  • 2
    I recommend editing the question with a [minimal, complete example](http://stackoverflow.com/help/mcve). The problem is not necessarily in this code. Also see [http://stackoverflow.com/q/299495/2891664](http://stackoverflow.com/q/299495/2891664). – Radiodef Apr 26 '15 at 10:37
  • 1) Change `ImageIcon imageIcon = new ImageIcon(imagePath);` to `ImageIcon imageIcon = new ImageIcon(fileChooser.getSelectedFile());` 2) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Apr 26 '15 at 10:39
  • Why is the title of the file chooser `"Choose directory"` when you expect the user to choose an (image) file and set the chooser to **not allow** directory selection? – Andrew Thompson Apr 26 '15 at 10:41
  • I have now added the information that you asked for! And it didn't work with the .getAbsolutePath(); – Darawan Apr 26 '15 at 10:47
  • I had "Choose directory" for another button and then copied the fileChooser code... – Darawan Apr 26 '15 at 10:48
  • Actually wait! It worked! Thanks so much MouseEvent! – Darawan Apr 26 '15 at 10:50

0 Answers0