问题
I am building a desktop app with Swing with similar functionality to Twitter. I have a "feed" page where "tweets" are displayed.
I have the "tweets" in a JPanel and want to dynamically display new ones coming in by placing new "tweets" at the top of the JPanel and moving older ones down. I was trying to do this with MigLayout by using jpanel.add(tweet, "cell 0 0, wrap")
however this didn't work as intended and in order to get it to display with the layout I wanted I had to call jpanel.revalidate()
.
This is not ideal as there could be many tweets coming in every second and redrawing the panel can be quite slow. Is there anyway I can add new "tweets" to the top of the panel without redrawing?
回答1:
Although dynamic layouts are possible, as shown here and here, I'd use a one-column JTable with a TableModel
that reflects the pushdown stack effect you want, perhaps one having an internal Queue<Tweet>
. JTable
rendering is efficient, and the component works well in a JScrollPane
.
回答2:
Short answer, no. Seriously, take a moment to think about the question. "I want to add new content, but not update the screen", how feasible do you think that is?
You're going to have to perform some kind of painting eventually. The question is how often.
However...
With some simple techniques (and modeling) you can "coalesce" the updates into batches, allowing the repaint to be more meaningful (rather then painting each new tweet, you paint a batch).
You could use something like a SwingWorker to do this. Basically publish
the tweet and allow the process
method to deal with adding the chunks afterwards.
来源:https://stackoverflow.com/questions/11927952/dynamically-rearrange-layout-with-swing