How to prevent memory leak in JTextPane.setCaretPosition(int)?

后端 未结 1 1102
一整个雨季
一整个雨季 2020-12-17 03:16

I\'m working on a Java application with Swing-based GUI. The application uses JTextPane to output log messages as follows: 1) truncate existing text to keep tot

相关标签:
1条回答
  • 2020-12-17 03:45

    The reason for this is that you are running the for loop in the event dispatch thread (see Event Dispatch Thread). This is the thread in which all user interface interactions happens.

    If you are running a long task, then you should run it in a different thread, so that the user interface keeps responsive. If you need to make a change on the user interface, like changing text in your JTextPane and setting the caret position out of a different thread than the event dispatch thread, you need to invoke either EventQueue.invokeLater() or EventQueue.invokeAndWait() (see EventQueue).

    I think the triggered events from setting the caret position are queued in your case and can only be processed, when the loop is finished (cause both are processed in event dispatch thread). So you should try something like this:

    @Override
    public void actionPerformed(ActionEvent e)
    {
      new Thread(new Runnable() {
        @Override
        public void run() {
          for (int i = 0; i < iter; i++)
          {
            final String display = String.format("%10d\n", i);
            try {
              EventQueue.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                  append(display);
                }
              });
            } catch (Exception e) {
              e.printStackTrace();
            }
          } // end for i
        }
      }).start();
    } 
    

    Might be even better if you call EventQueue.invokeAndWait only after x iterations and cache the previous results, which needs to be displayed.

    0 讨论(0)
提交回复
热议问题