【问题标题】:Chat Box area in Java SwingJava Swing 中的聊天框区域
【发布时间】:2022-01-10 10:04:51
【问题描述】:

我正在尝试调整 Java Swing 中的聊天框区域。它似乎在顶部,而我需要它在框架的底部。

我的代码:

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.Color;
import java.awt.event.*;
import javax.swing.border.Border;
import javax.swing.BorderFactory;
import java.lang.Override;
import java.lang.Thread;


import java.lang.Math;

public class ChatBot extends JFrame{
    
    private JFrame frame;
    private JTextArea chatArea;
    private JTextField chatBox;
    private JScrollPane scroll;
    private Border border;
    
    public static void main(String[] args){
        new ChatBot();
    }
    
    public ChatBot(){
        frame = new JFrame("Product Bot");
        chatArea = new JTextArea(20,50);
        chatBox = new JTextField();
        scroll = new JScrollPane(chatArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        border = BorderFactory.createLineBorder(Color.BLUE, 1);
        
        chatArea.setSize(540, 400);
        chatArea.setLocation(30,5);
        chatBox.setSize(540, 30);
        chatBox.setLocation(18, 18);
        chatBox.setBorder(border);
        frame.setResizable(false);
        frame.setSize(600, 600);
        frame.add(chatBox);
        frame.add(scroll);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        bot("Hello! I am a \"Product Bot\"! that answers product related queries! Ask me by typing below. Type \"QUIT\" to end the program. \n\n");
        chatArea.append("Chats: \n");
        chatBox.setText("");
        
        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")) {
                    sleep(500);
                    System.exit(0);
                }
                String category = "";
                try {
                        category = com.javavalley.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 "Sorry";
        }
        
}

P.S:添加了原型代码。我想要制作的是一个带有一些聊天历史的完整 GUI。我还想把它放在一个矩形窗口和一些 UI 改进中。

【问题讨论】:

标签: java swing jframe layout-manager


【解决方案1】:

是的,我希望按照您展示的方式进行。

如果底部文本字段被替换为JLabel(这里看起来更合乎逻辑),但布局相同,您可能会看到这种情况。

这是生成上面截图的代码。 (这也是一个 MRE,我希望你以后会发布。如果不是为了“填补原始代码的空白”,我本可以在一半的时间内解决问题)。

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;

class ChatBot {
    JFrame frame;
    JTextArea chatArea;
    JTextField chatBox;
    Border border;
    JScrollPane scroll;

    public ChatBot() {
        JPanel gui = new JPanel(new BorderLayout(5,5));
        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 below. Type \"QUIT\" to end the program.");
        chatArea.append("Chats: \n");
        chatBox.setText("Chat Box");

        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);
    }

    public static void main(String[] args) {
        new ChatBot();
    }
}

我忘记仔细记录所做的更改(在代码 cmets 中)。如果在仔细检查代码和相关 Java 文档后有任何您不理解的更改,请在评论中询问我,我会进一步解释。

【讨论】:

  • 我想知道有没有办法在 JFrame 中同时显示图像和文本?
  • 如果您想在 Swing 中混合文本和图像,请选择 EditorPane。比 TextArea 更复杂,但也更强大。
  • 通常最好将每个问题放在单独的线程上,但简短的回答是:JTextArea 是为纯文本构建的。要将图像和(格式化)文本嵌入到同一组件中,请查看支持“富文本”的组件,例如 JEditorPane
【解决方案2】:

您正在寻找一个布局。 这里我建议https://docs.oracle.com/javase/tutorial/uiswing/layout/border.html

无论如何,这是默认布局,所以你可以这样做:

public ChatBot(){
        ...
        frame.add(chatBox, BorderLayout.PAGE_START);
        frame.add(scroll, BorderLayout.PAGE_END);
        ...
}

您可以混合布局,并且应该创建将简单元素分组的面板。

【讨论】:

  • 我之前忘记了,但觉得这个答案值得一票,原因有 3 个。 1) 它链接到边框布局的教程。 2) 它使用逻辑而不是'罗盘'常量来放置组件(特别是LINE_STARTLINE_END 自动适应从左到右和从右到左的语言)。 3)提到可以组合布局。这种非常简单的布局没有必要,但我编写的 GUI 很少使用单一布局。
猜你喜欢
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 1970-01-01
  • 2014-10-06
  • 2010-12-04
  • 1970-01-01
相关资源
最近更新 更多