我有一个简单的 Java 程序,它读取一个文本文件,用“”(空格)分割它,显示第一个单词,等待 2 秒,显示下一个……等等……我想这样做在 Spring 或其他一些 GUI 中。
关于如何使用 spring 轻松更新单词有什么建议吗?遍历我的列表并以某种方式使用 setText();
我运气不好。我正在使用这种方法在 consol 中打印我的话并向其中添加 JFrame ...在 consol 中效果很好,但会产生无穷无尽的 jframe。我在网上找到了大部分。
private void printWords() {
for (int i = 0; i < words.size(); i++) {
//How many words?
//System.out.print(words.size());
//print each word on a new line...
Word w = words.get(i);
System.out.println(w.name);
//pause between each word.
try{
Thread.sleep(500);
}
catch(InterruptedException e){
e.printStackTrace();
}
JFrame frame = new JFrame("Run Text File");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel textLabel = new JLabel(w.name,SwingConstants.CENTER);
textLabel.setPreferredSize(new Dimension(300, 100));
frame.getContentPane().add(textLabel, BorderLayout.CENTER);
//Display the window. frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
我有一个使用 JFrame 和 JLable 创建的窗口,但是,我希望静态文本是动态的,而不是加载新的 Spring 窗口。我想它闪一个字,消失,闪一个字消失。
关于如何更新 JLabel 有什么建议吗?重绘()的东西?我正在画一个空白。
谢谢!
更新: 在下面好心人的帮助下,我已经将它正确打印到控制台。这是我的打印方法:
private void printWords() {
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListener() {
private Iterator<Word> w = words.iterator();
@Override
public void actionPerformed(ActionEvent e) {
if (w.hasNext()) {
_textField.setText(w.next().getName());
//Prints to Console just Fine...
//System.out.println(w.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
}
但是,它没有更新标签?我的构造函数看起来像:
public TimeThis() {
_textField = new JTextField(5);
_textField.setEditable(false);
_textField.setFont(new Font("sansserif", Font.PLAIN, 30));
JPanel content = new JPanel();
content.setLayout(new FlowLayout());
content.add(_textField);
this.setContentPane(content);
this.setTitle("Swing Timer");
this.pack();
this.setLocationRelativeTo(null);
this.setResizable(false);
//_textField.setText("loading...");
}
到达那里...一旦我或任何帮助我的人开始工作,我就会发布修复程序。再次感谢!
最佳答案
首先,构建并显示您的 GUI。显示 GUI 后,使用 javax.swing.Timer每 500 毫秒更新一次 GUI:
final Timer timer = new Timer(500, null);
ActionListener listener = new ActionListsner() {
private Iterator<Word> it = words.iterator();
@Override
public void actionPerformed(ActionEvent e) {
if (it.hasNext()) {
label.setText(it.next().getName());
}
else {
timer.stop();
}
}
};
timer.addActionListener(listener);
timer.start();
关于java - 从 ArrayList<List> 每 X 秒更新一次 JLabel - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943584/