简体   繁体   中英

Force repaint from another class - Swing

I basically have 1 class called ClueGame dedicated to painting the main gui using swing.

In this class, I iterate through a list of BoardCell objects, and call boardcell.draw(g) from within paintComponents(Graphics g), which draws rectangles to the board.

However, in a different class entirely, the WalkwayCell class (a child of BoardCell), I need to update the color of specific rectangles. I'm thinking something like cell.updateColor()

But obviously I need to get draw to do that some how. I don't know how to update the color of one object (rectangle) on the board because I can't call draw because I don't have a graphics object.

Hopefully that makes sense. I can post code if someone requests it.

You have any number of options...

You Could

Pass a reference of your ClueGame to the instances of WalkwayCell which would then be capable of calling repaint on the ClueGame reference directly.

The problem with this is you expose the entire ClueGame class to ever instance of WalkwayCell , which allows them to do whatever they want to it...

You Could

Use an observer pattern , to allow the ClueGame to monitor changes to the state of the WalkwayCell s

This means that WalkwayCell doesn't really care, it will simply provide some kind of event notification when the state of the object changes and doesn't expose parts of your application to other parts that have no right to know about...

Swing makes use of the observer pattern for it's listener API. You could take a look at Writing Event Listeners for some more ideas...

When creating a Swing GUI, it's important to create GUI model classes. The model classes hold the data for the GUI. Having model classes makes coding the Swing view classes so much simpler.

In your case, you would change the state of the instance of the WalkwayCell class, using a method like cell.updateColor(), as you suggested. First, you update the model instances. Then you draw the model instances on the view.

I've explained this concept in more detail with a working example in my Hangman Swing GUI article.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM