java - 如何更新 JScrollPane 内 JTextArea 的文本?

标签 java swing jscrollpane jtextarea

正如问题所述,我在更新 JScrollPane 内部 JTextArea 的文本时遇到问题。

我能够从 JScrollPane 的类型转换 getView() 中获取文本。 但是,我尝试了以下方法来更新 JTextArea。

((JTextArea)(chatWindow.getViewport().getView())).setText("Hello!");

其中 chatWindow 是 JScrollPane。

我已经尝试过这个:

chatWindowInsert.setText(processMessage()); 

其中 chatWindowInsert 是 JScrollPane 中的 JTextArea

不幸的是,两者都不起作用。

我没有遇到任何异常或挂起。

如有帮助,我们将不胜感激!

这是我的完整代码。如果我已经打破了一百万次编程实践,请非常原谅。

public class ChatterBotClient extends JFrame{

/**
 * 
 */
private static final long serialVersionUID = 1L;
private static ChatterBotFactory chatterBotFactory;
private static ChatterBotSession chatterBotSession;
private static ChatterBot chatterBot;
public static JScrollPane chatWindow;
public static JTextField userInput;
public static JTextArea chatWindowInsert;
public ChatterBotClient() 
{
    try{
    chatterBotFactory = new ChatterBotFactory();
    chatterBot = chatterBotFactory.create(ChatterBotType.CLEVERBOT);
    chatterBotSession = chatterBot.createSession();
    }catch(Exception e)
    {
        e.printStackTrace();
        System.out.println("Error :O");
        JOptionPane.showMessageDialog(null,
                "There has been a problem initializing the Bot. Please restart.");
    }

    initUI();
}

public void initUI()
{
    //Define the mainPanel that everything goes into in the JFrame
    JPanel mainPanel = new JPanel(new BorderLayout());
    //Define the child panels of "mainPanel"
    JPanel infoPanel = new JPanel(new FlowLayout());
    JPanel chatHistoryPanel = new JPanel(new FlowLayout());
    JPanel userInputAndButtonPanel = new JPanel(new FlowLayout());
    setTitle("ChatterBot Chat Client");
    setSize(600,300);
    setResizable(false);

    //Define each component
    //Set properties of each component
    JLabel infoLabel = new JLabel("Welcome to my Cleverbot Client! Please enjoy! :D");
        infoLabel.setPreferredSize(new Dimension(550, 20));
        infoLabel.setHorizontalTextPosition(SwingConstants.CENTER);

    chatWindowInsert = new JTextArea();
        chatWindowInsert.setWrapStyleWord(true);

    chatWindow = new JScrollPane(chatWindowInsert);
        chatWindow.setPreferredSize(new Dimension(500,225));
        chatWindow.setPreferredSize(chatWindow.getPreferredSize());


    userInput = new JTextField();
        userInput.setPreferredSize(new Dimension(250, 25));

    JButton enterBtn = new JButton("Send");
        enterBtn.setPreferredSize(new Dimension(75, 25));

    //Add each component to the required panels
    infoPanel.add(infoLabel);

    chatHistoryPanel.add(chatWindow);

    userInputAndButtonPanel.add(userInput, BorderLayout.CENTER);
    userInputAndButtonPanel.add(enterBtn, BorderLayout.EAST);

    //Add the child panels to the mainPanel
    mainPanel.add(infoPanel, BorderLayout.NORTH);
    mainPanel.add(chatHistoryPanel, BorderLayout.CENTER);
    mainPanel.add(userInputAndButtonPanel, BorderLayout.SOUTH);

    //Now, add the appropriate listeners to your components
    enterBtn.addActionListener(new ActionListener(){

        @Override
        public void actionPerformed(ActionEvent arg0) {
            System.out.println("You clicked me! :D");
            try {
                processMessage();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Something went wrong when you pressed the button! :O");
            }
        }
    });

    userInput.addActionListener(new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            chatWindow = new JScrollPane(new JTextArea(processMessage()));

        }
    });

    //Tell the JFrame to display what we've made!
    add(mainPanel);     

}

public static String processMessage()
{
    try {
        String completeMessage = chatWindowInsert.getText();
        completeMessage.concat("You: " + userInput.getText() + "\n");
        String response = chatterBotSession.think(userInput.getText());
        completeMessage.concat("Bot: " + response + "\n");
        userInput.setText("");
        return completeMessage;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return "ERROR";
    }
}

public static void main(String[] args)
{

    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            ChatterBotClient cli = new ChatterBotClient();
            cli.setVisible(true);
        }
    });
}

}

最佳答案

您声明:

As the question states, I'm having trouble with updating the text of a JTextArea that is inside of a JScrollPane.

I am able to grab the text from the typecasted getView() of the JScrollPane. However, I have tried the following to update the JTextArea.

((JTextArea)(chatWindow.getViewport().getView())).setText("Hello!");
<小时/> <小时/>

为什么要经历所有这些脆弱的代码练习?更简单、更安全、更容易的方法是创建一个类级 JTextArea 实例字段,然后将其显示在 GUI 中的 JScrollPane 中,并且只需在该实例上获取文本或设置文本即可。没有困惑,没有大惊小怪,没有错误。

如果您当前的程序无法做到这一点,那么您还没有告诉我们足够多的信息,因此您需要告诉我们更多信息。

<小时/>

编辑
回复您的评论:

have variables referencing both the JTextArea and the JTextField (just to try and figure this out) but even if I change either variable using one of the appropriate ways I described above, the contents inside of the JTextArea still won't change. Unless I'm not understanding what you're saying?

那么这表明虽然您可能正在使用正确的变量,但也许您正在使用错误的引用。也许您正在使用的变量未保存在当前显示的 GUI 中。

但这只不过是 SWAG 工作(愚蠢的疯狂猜测工作)。请不要强制我们猜测 - 编辑您的原始帖子并向我们展示您的代码,最好是 sscce ,向我们展示您如何获取这些变量的句柄以及如何知道它们属于显示的 gui。

<小时/>

编辑2
关于您的最新代码。让我们看看这一行:

public static JTextArea chatWindowInsert;
  1. 此字段不应是静态的,对此我 100% 确定。
  2. 您在哪里添加此字段最终引用的任何对象到您的 GUI?我在您发布的代码中找不到此内容。
<小时/>

编辑3

我现在看到,您将一个完全不同的 JTextField 放入 JScrollPane 中,从未将其放入 GUI 中的任何位置,并在所有位置按下按钮来完成所有这些操作!?

userInput.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent arg0)
    {
        chatWindow = new JScrollPane(new JTextArea(processMessage()));

    }
});

建议:

  1. 不要这样做。
  2. 每次激活此操作监听器时,不要创建新的 JTextArea 和新的 JScrollPane
  3. 不要创建组件,然后让它们闲置,不要将关键组件放置在 GUI 中。
  4. 在构建 GUI 时,请将 JTextArea 放入 GUI 中。一次且仅一次。

关于java - 如何更新 JScrollPane 内 JTextArea 的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20755234/

相关文章:

java - 将顶部与 JPanel 中新行中的每个元素垂直对齐

java - 以数据库为中心的 Java 应用程序的回归测试/测试自动化工具?

java - 通过 Java 在 ScrollPane 中绘制一个巨大的面板

java - 顶点数组的问题

java - sts 中的 Stackoverflow 异常

java - 使 JOptionPane 不区分大小写?

java - 在 SwingWorker 上使用 done 方法还是更改监听器更好?

java - 更改另一个类的 JLabel 文本

JScrollPane 中的 java 巨大的 BufferedImage

java 滚动条不合作