gpt4 book ai didi

java - 在运行时在 jtextArea 内添加随机单词,无需使用键盘

转载 作者:行者123 更新时间:2023-12-02 03:16:50 25 4
gpt4 key购买 nike

正如标题所说,我想在运行时添加 jtextArea 中的单词,我只是这样写:

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

public class Test extends JFrame {

private static final long serialVersionUID = 1L;
private JTextArea tarea;

public Test() {
tarea = new JTextArea(10, 10);
}

private void init() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
insertRandomLetterInsideJtextArea();
JScrollPane scroll = new JScrollPane(tarea);
getContentPane().add(scroll, BorderLayout.CENTER);
pack();
setLocationByPlatform(true);
setVisible(true);
}

private void insertRandomLetterInsideJtextArea() {
while (true) {
tarea.setText("foo\n");
}
}

public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test().init();
}
});
}
}

但它不起作用。 while(true) 不允许显示任何内容。有人可以解释一下为什么吗?

最佳答案

您应该使用计时器来实现此目的。试试这个:

package test;

import java.awt.BorderLayout;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Test extends JFrame {

private static final long serialVersionUID = 1L;
private JTextArea tarea;

public Test() {
tarea = new JTextArea(10, 10);
}

private void init() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JScrollPane scroll = new JScrollPane(tarea);
getContentPane().add(scroll, BorderLayout.CENTER);
pack();
setLocationByPlatform(true);
setVisible(true);
insertRandomLetterInsideJtextArea();
}

private void insertRandomLetterInsideJtextArea() {

Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
String content = "";
@Override
public void run() {
content += "foo\n"; // here generate your random String
tarea.setText(content);
}
}, 100, 1000); // firt is time before start, second is duration before repeat task, both in ms

}

public static void main(String... args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Test().init();
}
});
}
}

关于java - 在运行时在 jtextArea 内添加随机单词,无需使用键盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40176676/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com