【问题标题】:Java - Custom Image in JoptionPane.ShowConfirmDialog is not workingJava - JoptionPane.ShowConfirmDialog 中的自定义图像不起作用
【发布时间】:2023-03-14 01:17:01
【问题描述】:

当用户输入密码并点击确定按钮时,密码将被加密并存储在JTextArea。这工作正常。但我想在showConfirmDialogshowMessageDialog 弹出窗口中添加自定义徽标。我尝试使用以下代码,但自定义图像(徽标)未显示在消息弹出窗口中

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>

我将ImageIcon 对象作为参数传递给JoptionPane.showConfirmDialog。但是当我运行它时,我没有看到弹出窗口中显示任何图像。我不确定我在这里做错了什么。
注意:我需要在两个弹出窗口中都显示一个自定义图像。 showConfirmDialogshowMessageDialog
任何帮助将不胜感激

【问题讨论】:

    标签: java css


    【解决方案1】:

    您的代码非常好。我只是在我的环境中运行它,它运行良好。这使我相信您的问题是图像的路径。我什至用一个不存在的图像的路径来测试它,并且窗口显示没有显示任何图像。

    我只改了两件事,图片的路径明显:

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

    这张图片来自Free Icons PNG

    还有 Base64 类,因为没有提及您在哪里使用它,所以我使用 java 类:

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

    所以请确保您的图像 "C:\\Users\\Test\\Internet.png" 在磁盘上的那个路径上确实存在

    【讨论】:

    • 调整图像大小后现在可以正常工作了。我添加了这些行 ImageIcon icon = new ImageIcon(relativePath);图片 image = icon.getImage();图像 newimg = image.getScaledInstance(140, 140, java.awt.Image.SCALE_SMOOTH);图标 = 新 ImageIcon(newimg);
    • 爱书太好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    相关资源
    最近更新 更多