JLabel setText不更新文本 [英] JLabel setText not updating text
问题描述
我正在尝试使用setText()
方法更新JLabel,但无法重绘JLabel.我必须使用repaint()
方法来做到这一点吗?
I am trying to update a JLabel by using the setText()
method, but I can't redraw JLabel. Do I have to use the repaint()
method to do that?
这是代码的一部分,我没有收到任何错误,但是它没有更新JLabel.
Here is the part of code, I do not get any errors, but it is not updating the JLabel.
public void actionPerformed(ActionEvent e) {
fc = new JFileChooser();
if(e.getSource() == addButton) {
int returnVal = fc.showOpenDialog(Main.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
filesList = fc.getSelectedFiles();
setFilesList(filesList);
StringBuilder logString = new StringBuilder();
logString.append("Files to Convert " + "\n");
for(int i = 0; i < getFiles().length; i++) {
logString.append(filesList[i].getAbsolutePath());
}
//JLabel log = new JLabel(); created above.
log.setText(logString.toString());
} else {
//log.append("Open command cancelled by user." + newline);
}
//log.setCaretPosition(log.getDocument().getLength());
}
}
推荐答案
JLabel不需要重画调用.只需调用setText(...)即可更改标签的文本,仅此而已.
JLabel requires no repaint call. Simply calling setText(...) will change the label's text, and that is all that is required.
我想知道您的问题是否是并发问题,您是否正在Swing事件线程上执行长时间运行的过程,并且这是否在阻止标签更新其文本.
I wonder if your problem is a concurrency issue, that you are doing a long-running process on the Swing event thread and that this is preventing your label from updating its text.
如果是这样,那么考虑在诸如SwingWorker提供的后台线程中进行长时间运行的进程,然后在Swing线程上更新JLabel的文本,例如可以通过SwingWorker的发布/进程方法来完成.
If so, then consider doing your long-running process in a background thread such as that provided by a SwingWorker, and then updating your JLabel's text on the Swing thread, such as can be done via the SwingWorker's publish/process methods.
有关此内容的更多信息,请查看课程:Swing中的并发教程.
For more on this, please have a look at the Lesson: Concurrency in Swing tutorial.
也Mario De ...关于无法在JLabel上打印简单的换行符是正确的. 1 +.
Also Mario De... is correct about not being able to print simple new-lines on a JLabel. 1+ to his answer.
这篇关于JLabel setText不更新文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!