在 Java Swing 中将图像添加到 JFrame 中的文本

Adding Images to a text in JFrame in Java Swing

我正在构建一个聊天机器人应用程序,它根据主题和 returns 文本(答案)查询文本文件,并且还想显示与该主题 e.x Cricket 相关的图像。我能够正确查询和获取文本,但试图显示存储在我的文本文件所在位置的图像。我为此使用 ImageIcon。有什么方法可以用一张或多张图片生成文本吗?

package com.javavalley;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JScrollPane;

import java.awt.event.*;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.lang.Override;
import java.lang.Thread;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.lang.Math;

public class ChatBot extends JFrame{
    
    private JFrame frame;
    private JTextArea chatArea;
    private JTextField chatBox;
    private JScrollPane scroll;
    private Border border;
    
    private ImageIcon image1;
    private JLabel label1;
    private ImageIcon image2;
    private JLabel label2;
    
    public static void main(String[] args){
        new ChatBot();
    }
    
    public ChatBot(){


        JPanel gui = new JPanel(new BorderLayout(5,5));
        JPanel panel = new JPanel();
        JLabel label = new JLabel(new ImageIcon(getClass().getResource("SamsungJ2.png")));
        add(label);
        panel.setLayout(new FlowLayout());
        frame = new JFrame("Product Bot");
        frame.setContentPane(gui);
        chatArea = new JTextArea(10, 50);
        chatBox = new JTextField();
        scroll = new JScrollPane(chatArea,
                JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        border = BorderFactory.createLineBorder(Color.BLUE, 1);
        chatBox.setBorder(border);

        JLabel bot = new JLabel(
                "Hello! I am a \"Product Bot\"! that answers product related queries! " +
                "Ask me by typing above. Type \"QUIT\" to end the program.");
        chatArea.append("Chats: \n");
        chatBox.setText("");

        gui.add(chatBox, BorderLayout.PAGE_START);
        gui.add(scroll);
        gui.add(bot, BorderLayout.PAGE_END);
        gui.setBorder(new EmptyBorder(5,5,5,5));
        frame.setResizable(false);
        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        chatBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                String gtext = chatBox.getText();
                chatArea.append("You: " +gtext + "\n");
                chatBox.setText("");
                if(gtext.equals("QUIT")|gtext.equals("quit")|gtext.equals("exit")) {
                    sleep(500);
                    System.exit(0);
                }
                String category = "";
                try {
                        category = ProBot.findCategory(gtext);
                        System.out.println(category);
                }
                catch (Exception e) {
                    System.out.println("Exception thrown.");
                }
                String response = respond(category);
                bot(response);
                }
            }); 
        
    }
        
        private void bot(String string)
        {
            chatArea.append("Bot: " + string + "\n");
        }
        
        
        private void sleep(int x) {
            try {
                Thread.sleep(x);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        
        private String respond(String category)
        {
            String[] greetings = {"Hello, how can I help you?"};
            String[] conversationContinue = {"How can I help you with?", "What else can I help you with?"};
            String[] colorsinquiry = {"Black, Blue, Green, Red, Sierra Blue"};
            String[] priceinquiry = {"Price is EUR 279"};
            String[] productinquiry = {"Product is an Android 11 smart phone with latest features like Super AMOLED Display, 6.5 inches, Li-Ion 5000 mAh, non-removable battery, Octa-core (4x1.6 GHz Cortex-A55 & 4x1.2 GHz Cortex-A55))"};
            String[] conversationComplete = {"Goodbye", "Bye", "Nice chatting with you. Bye!"};
            
            if (category.equals("greeting")) return greetings[(int) (Math.random()*greetings.length)];
            else if (category.equals("colors-inquiry")) return colorsinquiry[(int) (Math.random()*colorsinquiry.length)];
            else if (category.equals("price-inquiry")) return priceinquiry[(int) (Math.random()*priceinquiry.length)];
            else if (category.equals("product-inquiry")) return productinquiry[(int) (Math.random()*productinquiry.length)];
            else if (category.equals("conversation-continue")) return conversationContinue[(int) (Math.random()*conversationContinue.length)];
            else if (category.equals("conversation-complete")) return conversationComplete[(int) (Math.random()*conversationComplete.length)];
            else return "Err.. :( Sorry, I did'nt get that!";
        }
        
}

然而,它给了我NullPointerException

Exception in thread "main" java.lang.NullPointerException
        at java.desktop/javax.swing.ImageIcon.<init>(ImageIcon.java:217)
        at com.javavalley.ChatBot.<init>(ChatBot.java:40)
        at com.javavalley.ChatBot.main(ChatBot.java:32)

我的UI

删除 add(label),并将 frame.setContentPane(gui); 替换为以下内容,例如:

frame.getContentPane().add(gui, BorderLayout.NORTH);
frame.getContentPane().add(label, BorderLayout.SOUTH);

您也可以在 gui 中添加标签(例如,gui.add(panel)),然后只将面板添加到框架中。