Call repaint of an other Component - java

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.

Related

Can't understand JPanel setBackground method behavior

JPanel.setBackground method does nothing (although opaque attribute is true) if super.paintComponent father method isn't being called.
I have read a lot of similar questions here about this issue, and in each one of them I've only found solutions without explanation that helped me to understand why setBackground method when written before adding the JPanel to JFrame changes the JPanel background color, while when the setBackground is written inside paintComponent nothing is changed (only when calling father's paintComponent method as already mentioned).
Is it somehow related to Graphics object?
I have tried to change JPanel's opaque attribute to true and using setBackground(COLOR.BLACK) in paintComponent() method I had overriden in a class that extends JPanel
paintComponent(Graphics g)
{
this.setOpaque(true);
this.setBackground(COLOR.BLACK);
}
I expect that the JPanel background color will be black
Instead, background color is the default one
Well, first of all if you're using paintComponent(Graphics g) method, the first line you need to have inside is: super.paintComponent(g) otherwise you're breaking the paint-chain.
This will allow the parent component to draw the default component, before any customizations you do to it. If you don't do it, well, is like having a drawing in a piece of paper, imagine a circle, then cutting that circle and then trying to paint the outside.
Here's a more in-depth answer to How does super.paintComponent(g) works
However I wouldn't write
this.setOpaque(true);
this.setBackground(COLOR.BLACK);
inside the paintComponent(...) method, as it gets called several times and you can't control when it will ever get called. I would put those lines in a constructor, unless you want to change it later in your program while it's being painted depending on the state of your program or a gradient maybe.
For this part:
why setBackground method when written before adding the JPanel to JFrame changes the JPanel background color
Honestly, I don't understand what you mean.
Why do you say that if i won't call super.paintComponent(),it will break the chain? It's still drawing all the shapes and lines i want using graphics object.
From the docs:
The JPanel has a UI delegate which performs the background painting for itself. You call it by using super.paintComponent(g) and we pass the Graphics component to prevent irrevocable changes such as Graphics.translate
Your JPanel knows how to paint its children, but requires some help to paint itself, and this help comes from its parent.
When I mentioned "break the paint chain" I didn't mean nothing would paint, but that you would get strange behaviors such as the one of the JPanel's background disappearing or not being set.
In addition,something weird happens if the argument i'm sending to setBackground method is a random color(using Random object). JPanel changing color very quickly although i'm not doing anything(not minimizing,not resizing,etc).Can you consider why?
As I said before, the paintComponent gets called several times and you don't have control over when it will be called, even moving your mouse or something else will trigger the panel to repaint.

Using swing components with an applets paint method

I have a functioning Java applet which can be embedded into a web page and wish to now add some swing components for additional functions. However whenever I add a component like a JLabel, it simply does not appear on the viewport/canvas unless I remove my entire paint method. The latter option allows me to add swing components but naturally I then cannot render any shapes. It appears to resemble an eXclusive OR (XOR), either one but not the other.
Is there anyway in a native Java applet to add swing components and still maintain the paint(Graphics g) method. Please note that I am inheriting from Applet and not JApplet.
If you override paint method in applet then there is no simple way.
What you could do instead of overriding paint in applet.
Extend JComponent instead and do the custom drawing there.
create JPanel that contains all the needed swing components including the component from earlier step.
Add that panel to applet which is using default paint method.
I suggest that you add the components to a separate panel that doesn't override paint. By overridding paint, you are customizing the way the component is drawn, so the layout manager and the components it has to manage do not count, it's only the implementation of paint you wrote that dictates how stuff is rendered.
So, your applet would contain a panel with the components and a panel that does the custom painting.
At the end of your paint method, call super.paint(g).
I was able to visualise the components over the applet canvas by invoking
paintComponents(g);
Thus the components are thereafter painted AFTER the actual paint(Graphics g) method completes its epoch.

Flickering while revalidating JPanel

I have looked all round, and no one seems to have an answer for me. I have a JPanel where I add/remove labels from it while it;s running. The problem is that every time I add a new label to it I have to revalidate() it so the new label shows up. Every time I revalidate(), it I get a very annoying flicker, and all my labels ghost up to the top of my window for a millisecond then return to what they were doing. The only time I call revalidate() is after I add a label; I do not change the paint method or anything only did
public void paintComponent(Graphics page)
{
super.paintComponent(page);
}
so that my page would not look bad. I could really use some help on this. I've made a asteroids game using JFrame, Jlabel and Jpanel game; it work great, but this flickering and component "ghosting quickly ghosting to top of panel" is just unbearable, and I know for a fact this is the revalidate() method.
Using labels (or generally GUI components) to represent quickly animating, dynamically created/moved objects is not practical. Its like using a car to drive from the living room to the kitchen.
The Swing components come with a lot of nice features, e.g. they can determine the space they require and a layout manager can use that to automatically place them nicely. Unfortunately for a game, you neither need all the nice stuff, nor do you want to pay the processing overhead involved with it. Matters are further complicated by swings multi-platform capabilities which mandate that each component has a peer component (the peer deals with rendering the component to the active look).
To solve this, you do not represent individual game objects as swing components. Instead you use a single swing component (usually JPanel) as a canvas to paint your game objects on to. You simply call repaint() for that JPanel periodically (e.g. 30 or 60 times a second). Of course you will override paintComponent() on the JPanel to do paint all the game objects using your own code.
Edit: To outline how you do your own rendering
You need to decide how to organize your game related objects. A very simple skeleton could look like this (getters/setters omitted):
public class GameObject {
public int x;
public int y;
public Image image;
}
In practice this class will have additional members (like a behavior that controls how the object moves, and maybe some states/counters for animation). It may also be abstract with a concrete subclass for each possible behavior (like ship, asteroid and bullet). All instances of GameObject are managed in some kind of collection, I assume you use a List.
When implementing the paintComponent it comes down to just loop through the list and render each objects's image:
public void paintComponent(Graphics g) {
List<GameObject> list = ... // however you obtain it in your game
for (GameObject gobject : list) {
g.drawImage(gobject.image, gobject.x, gobject.y, (ImageObserver) null);
}
}
More elaborate games may order the gameobjects to get control of how game objects overlap each other. But in principle its incredibly simple.
When I was having problems with filckering Swing components it turned out to be concurrency issues. Since you are doing a game, which means you are doing animation it may be the case here.
Take care to modify Swing components only from AWT-EVENT thread. Either use SwingUtilities.invokeLater or do your animation using javax.swing.Timer.
As a concrete example, Asteroids doesn't flicker at all. Here are a few reasons:
It runs on the event dispatch thread.
It uses JPanel, which is double buffered by default.
It paces the animation using javax.swing.Timer, updating the game's model in actionPerformed().
It overrides paintComponent(), but can safely omit super.paintComponent() because the action listener repaints the entire panel.
The listener calls paintImmediately() to avoid any potential delay; substitute repaint() to see if there's any difference on your platform.
Addendum: As shown in this counter-example, revalidate() does not cause flickering. Instead of replacing labels, update the label's icon, as shown here.
Have you considered reusing them - i.e. using setVisible(false) when they're not needed?
Not sure if adding and removing labels is the best way of achieving what you want for a game.
I'd personally be tempted to manage the drawing myself.

Multi Threading and graphics

My project is based on multi threading and graphics. The problem is in calling repaint() method. I am trying to call repaint method from class second which implements runnable and paint() method is in class first extending Canvas. But repaint not working.
What should I do?
Thnx
It would be much wise, that instead of using Canvas, if you override the paintComponent(...) method of a JComponent and paint on it, instead of overriding paint(...) method.
The Component.repaint() method, under Swing in particular, only marks the component as needing a repaint, it doesn't actually trigger the repaint directly.
Make sure you allow other threads to run by calling Thread.yield(), as it's the main graphics thread (which launched your other thread(s)) that actually checks the components to see what needs to be repainted.

Content of JDesktopPane dissappears when resized - Java Swing

I have been working on Java Swing for a while. I paint something(draw some basic shapes like circle,rectangle etc) on a JDesktopPane and once I resize the frame window that contains jDesktopPane or drag some other window over this frame, then the drawn shapes disappear. I use an object of the BufferedImage class so as to save the image. So Is there any way of preventing the shapes getting disappeared or repaint it when they disappear?
You need to make sure you are saving what you paint and repainting it each time in the paintComponent() method. This method is called automatically whenever a repaint is needed (for example: because of a resize).
I can only provide a guess since you've decided not to post the necessary code, but my suggestions are:
Don't get your Graphics object by calling getGraphics on a component. Instead,
Be sure to do your drawing in a class that subclasses a JComponent or one of its children (such as a JPanel).
draw your BufferedImage in the JComponent's paintComponent method immediately after calling super.paintComponent() in the same method. Use the Graphics object that is provided by the JVM and passed into the method's parameter.
To be sure that your paintComponent method's signature is correct, place an #Override annotation immediately before it. Otherwise if it is not correct, the JVM will probably not call it when you expect it to.
But also, please when asking a question here, try to give us enough information so we don't have to guess. Since your problem is graphics related, it would make sense to post your graphics-related code, right?

Categories

Resources