Question

Currently, I have a JFrame that contains a JPanel. The JPanel is the paint for my program. Paint meaning all of my Graphics g.drawString things. Right now, it only updates the display whenever the user interacts with the JFrame, but I want it to continuously update (repaint()) itself WITHOUT using a while loop (too much CPU usage).

Anyone know how I could do this?

Was it helpful?

Solution

What you need to do is to inform the swing component whenever you know that part of the image on your panel changed. The normal way to do this is to, as you said, call repaint() and if you know the rectangle that was 'invalidated' you can also indicated that.

Depending on the events that cause the contents of the JPanel, you need to change your application design so that the presentation part of your application 'listens' to changes in the data underneath and repaints when these changes occur.

There is another method called paintImmediately() which might do for certain situations, but you have to describe a little more your scenario and in which cases are you needing to repaint continuously.

OTHER TIPS

I have implemented a fully functional internet relay chat system which involves paint to see what you and other people are saying

It sounds like you are trying to "pull" updates from the server, then you can use a SwingWorker to query the server for updates and then pulish the updates to the GUI. You would want the SwingWorker to sleep so it doesn't continuously poll the server.

Read the section from the Swing tutorial on Worker Threads and SwingWorker for more information.

Maybe a better design is for the server should "push" updates to the client and the client should listen for changes and then repaint itself. Maybe the All About Sockets section will help you out.

Edit:

Here is some old code I havent looked at in over 5 years. The "client" is a simple text pane which sends each character typed to the "server". The server then sends each character to any other client that is connected to the server. The idea it that the server has the most up to date Document. As one client sends a change all other clients are notified of the change. This way all clients always contain the same data. Your code should be simpler since you will only send complete messages to the server. To run the code open a dos window and type:

java DocumentServer 1234

This will start a server that listens to port 1234

Then open another window and type

java DocumentClient 1234 3

This will create 3 client frames that connect to the server. Typing in either of the frames will update the server.

You can get the zip file here:

http://www.camick.com/java/source/echo.zip

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top