简体   繁体   中英

Call repaint of an other Component

I'm doing some small Java program for college and i'm running into a problem to redraw some Graphics after an update. Here's the context:

I have a main Jframe which contains basically two things, a JComponent used to draw/paint some Graphics (Rectangles, Circle, etc) and a JMenu to give sort options to the user.

The JComponent overrides paintComponent so I can draw the Graphics upon request. The Graphics are customs classes with methods to define the type of Graphic and each will call their own drawRect() or drawOval(). That is working very well. If I call repaint() for the main JFrame it will call paintComponent of the JComponent() as expected.

One of the menus in the JMenu has options to sort the Graphics per different order. So in my ActionListner of each options I proceed with the sort of the LinkedList containing the Graphics.

The problem is when im done with the sort in the ActionListener, I would call repaint() to draw the Graphics in the JComponent but it will call the repaint() of the JMenu instead... So my question is how to somehow call the repaint of the JComponent from the JMenu?

Thanks.

One of the menus in the JMenu has options to sort the Graphics per different order. So in my ActionListner of each options I proceed with the sort of the LinkedList containing the Graphics.

Then that code should invoke repaint() on the component. That is LinkList should be part of the component that paints the Graphics. So you would have a method like sort(...) that you invoke on the component. The method would then do the sort and then repaint() the component.

This is the way all Swing methods work, like setText(...) , setBackground(...) . You invoke these methods on the component and then the component invokes repaint() on itself.

The key is to make sure that the calling code has a clean reference to the viewed object of the called code. In other words, the listener code for your menu needs a reference to the drawing JComponent, usually placed into a field of the listener's class. How you pass it in will depend on the structure of your program. This can be done via a constructor parameter, or if you want to be cleaner, via dependency injection.

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