当前位置: 首页 > 知识库问答 >
问题:

JTextPane/JTextArea append()随机工作

华知
2023-03-14

我在一个非常简单的GUI中有一个JTextPane,我将它用作学习Java的游戏的输出控制台,我(尝试)将它与Windows类中的append方法一起使用,从另一个类(程序本身)或从command reader类调用它。理论上,它应该输出我输入的命令,在下几行中,它的输出来自所述程序。

import java.awt.*;
import java.awt.event.*;

import javax.swing.*;
import javax.swing.border.*;
import javax.swing.text.DefaultCaret;

import graficos.VisorJugador;

public class test extends JFrame {
      private static final long serialVersionUID = 1L;
      private JPanel contentPane;
      private String comando = "";
      private JTextArea txp_Console;
      private JScrollPane jsp_ConsoleScrollPanel;
      private JLabel lbl_habitacion;
      private VisorJugador[] jugadores;
    
    /**
     * Create the frame.
     */
    public test() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 640, 480);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);
        
        createPanels();
    }
    
    public static void lanzar(test frame){
        frame.setVisible(true);
    }
    
    private void createPanels(){
        JPanel panelInferior = new JPanel();
        JPanel panelCentral = new JPanel();

        panelCentral.setLayout(new BorderLayout(0, 0));

        crearInferior(panelInferior);
        crearCentral(panelCentral);

        contentPane.add(panelInferior, BorderLayout.SOUTH);
        contentPane.add(panelCentral, BorderLayout.CENTER);
    }
    
    private void crearCentral(JPanel panelCentral) {
        JLabel lbl_Consola = new JLabel("Consola");
        txp_Console = new JTextArea();
        jsp_ConsoleScrollPanel = new JScrollPane(txp_Console);
        
        txp_Console.setEditable(true);
        
        DefaultCaret caret = (DefaultCaret) txp_Console.getCaret();
        caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
        
        panelCentral.add(lbl_Consola, BorderLayout.NORTH);
        panelCentral.add(txp_Console, BorderLayout.CENTER);
    }
    
    private void crearInferior(JPanel panelInferior) {
        JLabel lbl_QueHacer = new JLabel("Que quieres hacer?");
        JButton btn_Enviar = new JButton("Hacer");
        JTextField txt_consola = new JTextField();

        btn_Enviar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                comando = txt_consola.getText();
                print("> " + txt_consola.getText());
                txt_consola.setText("");
            }
        });
        txt_consola.setColumns(10);
        
        panelInferior.add(lbl_QueHacer, BorderLayout.NORTH);
        panelInferior.add(txt_consola);
        panelInferior.add(btn_Enviar);
    }
    
    public void print(String texto) {
        String anterior = txp_Console.getText();
        txp_Console.setText(anterior + texto);
    }
}

另外,这里有一些示例输出

No entiendo  --From commands 2 and 3
No entiendo  --From commands 2 and 3
Bienvenido al Mundo de Zuul!  --Working output
El Mundo de Zuul es un juego de aventuras muy aburrido, pero interesante!.  --Working output
Escribe 'ayuda' si necesitas ayuda.  --Working output
Estas en el exterior de la entrada principal de la universidad  --Working output
    Salidas: este, sur, oeste  --Working output
> 1           --Works as intended
No entiendo   --Output for command 1
> 2           --Output at the top
> 3           --Output at the top
> 4           --No output, windows error sound

在调试过程中,我看到为Swing/AWT创建了一个线程,但我根本不了解线程,所以我只希望我不需要线程。我也试过设置羽毛笔,移动滚动条,从命令中移除“/n”,但没有成功。

共有1个答案

濮阳宜
2023-03-14

您对线程的使用可能是错误的,但我们没有看到有问题的代码,所以很难判断。我将声明的一件事是,您应该始终在Swing事件线程上启动您的GUI,并且应该努力在同一线程上对您的GUI进行更改。

您可以对print方法进行的一个更改是测试您是否在Swing事件线程上,如果是,则将传入的文本追加到JTextArea。如果没有,则使用SwingUtilities创建代码,在事件线程中对此更改进行排队,如下所示:

public void print(String texto) {
    // String anterior = txp_Console.getText();
    // txp_Console.setText(anterior + texto);
    if (SwingUtilities.isEventDispatchThread()) {
        // if on the Swing event thread, call directly
        txp_Console.append(texto);  // a simple append call is all that is needed
    } else {
        // else queue it onto the event thread
        SwingUtilities.invokeLater(() -> txp_Console.append(texto));
    }
}

请阅读“Swing中的并发”课程,了解有关Swing线程的更多信息。

例如,假设我有一个GUI,如下所示:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;

@SuppressWarnings("serial")
public class JuanjoTestPanel extends JPanel {
    private static final int TA_ROWS = 25;
    private static final int TA_COLS = 60;
    private JTextArea textArea = new JTextArea(TA_ROWS, TA_COLS);
    private JTextField textField = new JTextField(30);
    private Action hacerAction = new HacerAction();

    public JuanjoTestPanel() {
        textArea.setFocusable(false);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textField.setAction(hacerAction);
        JPanel bottomPanel = new JPanel();
        bottomPanel.add(new JLabel("¿Que queres hacer?"));
        bottomPanel.add(Box.createHorizontalStrut(5));
        bottomPanel.add(textField);
        bottomPanel.add(new JButton(hacerAction));

        setLayout(new BorderLayout());
        add(scrollPane);
        add(bottomPanel, BorderLayout.PAGE_END);
    }

    public void printToWindow(final String text) {
        if (SwingUtilities.isEventDispatchThread()) {
            textArea.append("Console:" + text + "\n");
        } else {
            SwingUtilities.invokeLater(() -> textArea.append("Console:" + text + "\n"));
        }
    }

    private class HacerAction extends AbstractAction {
        public HacerAction() {
            super("Hacer");
            putValue(MNEMONIC_KEY, KeyEvent.VK_H);
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            String text = "> " + textField.getText() + "\n";
            textArea.append(text);
            textField.selectAll();
            textField.requestFocusInWindow();
        }
    }
}

您还可以通过调用其PrintToWindow(...)方法从控制台写入它,如下所示:

import java.util.Scanner;
import javax.swing.*;

public class TestSwing2 {

    private static final String EXIT = "exit";

    public static void main(String[] args) {
        // create window
        final JuanjoTestPanel testPanel = new JuanjoTestPanel();
        // launch it on the Swing event thread
        SwingUtilities.invokeLater(() -> createAndShowGui(testPanel));
        Scanner scanner = new Scanner(System.in);
        String line = "";
        while (!line.trim().equalsIgnoreCase(EXIT)) {
            System.out.print("Enter text: ");
            line = scanner.nextLine();
            System.out.println("Line entered: " + line);
            testPanel.printToWindow(line); // write to it
        }
        scanner.close();
        System.exit(0);
    }

    private static void createAndShowGui(JuanjoTestPanel testPanel) {
        JFrame frame = new JFrame("Test Swing2");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(testPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
 类似资料:
  • 说明 RandomUtil主要针对JDK中Random对象做封装,严格来说,Java产生的随机数都是伪随机数,因此Hutool封装后产生的随机结果也是伪随机结果。不过这种随机结果对于大多数情况已经够用。 使用 RandomUtil.randomInt 获得指定范围内的随机数 RandomUtil.randomBytes 随机bytes RandomUtil.randomEle 随机获得列表中的元素

  • 字符串随机 Random::randStr(6); 纯数字字符串随机 Random::randNumStr(6);

  • 问题内容: 有没有什么方法可以模拟Collections.shuffle的行为,而比较器不容易受到排序算法实现的影响,从而确保结果安全? 我的意思是不违反可比合同等。 问题答案: 不打破合同就不可能实现真正的“改组比较器”。合同的一个基本方面是,结果是可 重现的, 因此必须确定特定实例的顺序。 当然,您可以使用混洗操作预先初始化该固定顺序,并创建一个比较器来精确地建立此顺序。例如 虽然没有意义。显

  • 是否有任何方法可以模拟Collections.shuffle的行为,而比较器不容易受到排序算法实现的影响,以确保结果安全? 我的意思是不违反类似的合同等..

  • 我最近用一个简单的算法制作了一个机器人。机器人应该在某个频道欢迎你,然后你必须告诉他你的名字级别(在某个游戏中)和你的团队(团队1、团队2或团队3)。当你这样做时,他应该以你的昵称和级别命名你,并以你的团队设置你的不和谐角色。最后,在他这样做之后,他会要求你在pm上提供你个人资料的截图,并在另一个频道发送截图(这不是重要部分)。 命名部分和屏幕截图功能工作正常,但出于未知原因,setRole功能似

  • 问题内容: 我只想在JTextPane中的某些文本上添加一些工具提示。例如,如果JTextPane中有参考链接文本,我想在该文本中添加工具提示以显示链接。有什么办法可以实现此功能? 问题答案: 好问题。 First Swing支持HTML,因此要显示带有链接的工具提示,您只需说: 问题是使此工具提示可单击。 不幸的是,它不是由Swing本身完成的。 工具提示由ToolTipManager创建。当您