Java - Custom image in JoptionPane.ShowConfirmDialog not working

When the user enters the password and presses the "OK" button, the password will be encrypted and stored in JTextArea . And it works fine. But I want to add a custom logo to the showConfirmDialog and showMessageDialog . I tried using the code below, but the custom image (logo) does not appear in the message popup

 public static void main(String[] args) { Box box = Box.createHorizontalBox(); JLabel label = new JLabel("Enter your password : "); box.add(label); JPasswordField passwordField = new JPasswordField(24); box.add(passwordField); final ImageIcon icon = new ImageIcon("C:\\Users\\Test\\Internet.png"); int button = JOptionPane.showConfirmDialog(null, box, "Enter your password", JOptionPane.OK_CANCEL_OPTION, JOptionPane.NO_OPTION, icon); if (button == JOptionPane.OK_OPTION) { String password = new String(passwordField.getPassword()); String encryptedPassword; if (password != null && !password.equals("")) { byte[] bytesEncoded = Base64.encodeBase64(password.getBytes()); JTextArea richTextField = new JTextArea(10, 10); encryptedPassword = new String(bytesEncoded); richTextField.setText(encryptedPassword); richTextField.setOpaque(false); richTextField.setEditable(false); JOptionPane.showMessageDialog(null, richTextField); } else { JOptionPane.showMessageDialog(null, "Password cannot be null. Please enter password to encrypt."); } } }<br> 

I pass the ImageIcon object to JoptionPane.showConfirmDialog as an argument. But when I run this, I do not see the image displayed in the popup. I'm not sure what I'm doing wrong here. Note. I need to create my own image that will be displayed in both pop-ups. showConfirmDialog and showMessageDialog
Any help would be greatly appreciated.

0
java css
Mar 17 '17 at 10:49
source share
1 answer

Your code is ok. I just ran it in my environment and it worked fine. It makes me think that your problem is the path to the image . I even tested it using the path for an image that was not there, and the window shows up without displaying the image.

I just changed two things: the path to the image, obviously:

 final ImageIcon icon = new ImageIcon("c:\\temp\\poke-ball-png-13_30x30.png"); 

enter image description here

This image I got from Free PNG icons

And the Base64 class, since there is no mention of where you use it. I use java one:

 import java.util.Base64; .... byte[] bytesEncoded = Base64.getEncoder().encode(password.getBytes()); 

Therefore, make sure that your image "C:\\Users\\Test\\Internet.png" is actually on disk along this path

+1
Mar 17 '17 at 12:30
source share



All Articles