Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

java - JLabel setText not updating text

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?

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 " + "
");
                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());
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

JLabel requires no repaint call. Simply calling setText(...) will change the label's text, and that is all that is required.

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.

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.

For more on this, please have a look at the Lesson: Concurrency in Swing tutorial.

Also Mario De... is correct about not being able to print simple new-lines on a JLabel. 1+ to his answer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...