I have been developing on my Mac a JAVA Applications . The logic is as follows:
A Server sends to a client application some orders to Draw basic shapes
The client applications draws the the basic shapes into a Jpanel
Every Time a Shape arrives the program calls repaint()
public void paintShape(Shape p)
{
//this.paintComponent(this.getGraphics());
arrayofShapes.add(p);
this.repaint();
//this.updateUI();
//this.update(this.getGraphics());
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g2d = (Graphics2D) g.create();
g2d.setStroke(new BasicStroke(2));
g2d.setColor(pickedColor);
for(final Shape p : arrayofShapes)
{
g2d.draw(p);
}
//g2d.dispose();
}
Everything works smoothly(on real time) , so I decided to test the same application on a Windows computer. The result is a laggy application. These are the conclusion that I have reached.
RepaintManager is accumulating repaint() calls. I see how the shapes arrive at destination but in some cases more than 5 repaint calls are accumulated into one, which make the application very lagged/not real Time.
I have tried instead of calling repaint every time a shape arrives to do it with a Timer every few milliseconds, the result is the same. Code :
ActionListener listener = new ActionListener(){
public void actionPerformed(ActionEvent event){
repaint();
}
};
Timer displayTimer = new Timer(5, listener);
displayTimer.start();
In addition i have tested some random code that allows you to paint with the mouse, same logic as mine with paintComponent. In this case it work smoothly without sense of lag.... Example: http://javagraphics.blogspot.com.es/2010/06/shapes-implementing-freehand-pencil.html
I do not understand why paintComponent is so slow on my Windows Computer(same Jar). What could be affecting the performance of my program?
I have read all the answers regarding paint Components but any of them has solved this issue.
Any advice on how could I solve the problem and actually archive Real-Time?
Thank you in advance
Update Videos:
Mac Video:https://youtu.be/OhNXdGXoQpk real Time no problem handling heavy load
Windows Video https://youtu.be/yol2miHudZc clearly laggy
I apologize for the low quality
Update BufferedImage:
After introducing the BufferedImage the result is still a slow painting Application. It creates another problem, since one of the orders is to delete all shapes, it adds some complexity since I have to do a :
g2d.clearRect(0, 0, screenSize.width, screenSize.height);
HW/OS/JavaVersion
Windows
Processor i5-4300u 2.5ghz
Ram 12gb
Java version 1.7.0_71
MAC
Processor i7 2.9ghz
Ram 8gb
Java version 1.7.0_67
Java VisualVM
Video of live VisualVM:https://youtu.be/cRNX4b3rlZk
I do not see anything strange that could explain why the lag occurs but I'm far from being an expert(Again sorry for low quality)
Thank you for all your responses
There's no need to create() a new graphics context each time; just cast g to Graphics2D. This is safe on all concrete implementations. This also obviates the need to dispose() of the created context. As noted here, preserve any context variables that may be critical for later painting.
public void paintComponent(Graphics g) {
super.paintComponent(g);
g2d = (Graphics2D) g;
Stroke oldStroke = g2d.getStroke();
g2d.setStroke(new BasicStroke(2));
g2d.setColor(pickedColor);
for(final Shape p : arrayofShapes) {
g2d.draw(p);
}
g2d.setStroke(oldStroke);
}
Also, compare the profiles on both platforms to look for disparities. For reference, the example cited here comfortably handles selections containing hundreds of shapes on either platform.
I would recommend that you do static drawing to a BufferedImage, and then draw the BufferedImage in your paintComponent method.
e.g.,
private BufferedImage bufferedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, BufferedImage.TYPE_INT_ARGB);
public void paintShape(Shape p) {
Graphics2D g2 = bufferedImage.createGraphics();
g2d.setStroke(MY_STROKE); // make this a constant
g2d.setColor(pickedColor);
g2d.draw(p);
g2d.dispose();
this.repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (bufferedImage != null) {
g2.drawImage(bufferedImage, 0, 0, null);
}
// do dynamic drawing such as drawing of moving sprites here
}
After more than two days of debugging I have found out that the problem has nothing to do with paintComponent()
With the same server generating random shapes
At the Windows app, some shapes are received at the same time which is impossible since I am sending shapes every 15 ms. That's why it accumulates shapes(result =lag).
On the other Hand at the Mac app, every shape has different time reception (result = real Time)
Thank you for the kind responses, and sorry for inconvenience I may have cause
Related
I'm working on some animation where I have a certain number of dots wandering around my JFrame and based on their distance they should be connected by lines of different strengths.
The base code for moving the dots works and actually I also had them displayed correctly in the beggining but I had some issues where the movement was stuttering (probably due to the repaint process). At that point the Window class handled the entire repaint procedure.
After reading some posts around here I adapted my code according to the github page linked in this post to use the individual Dots as JComponents and have them being repainted individually. However, now the problem is that although I still have 100 Dots as components on my JPanel, only one of them is being painted (however, the stuttering is gone at least). I also see that all components are being iterated and their repaint method is being called but they just don't display.
This is my paintComponent method in the Dot class:
#Override
protected void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(new Color(0, 0, 0));
Ellipse2D.Double circle = new Ellipse2D.Double(x - 10 / 2, y - 10 / 2, 10, 10);
g2d.fill(circle);
}
And this is what my repaintTimer looks like:
final Timer repaintTimer = new Timer(20, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for(Component component : window.getContentPane().getComponents()) {
component.repaint();
}
recalculateDots();
}
});
repaintTimer.start();
The result I get is something like this:
I tried some things of which I thought that it could solve the problem but nothing really helped and I'm really confused as to why this is happening. I'd appreciate any help very much because this issue doesn't make any sense for me.
I am trying to make an animation by Java but having trouble understanding the DoubleBufferImage and DoubleBufferGraphics. I understand about the update(), render(), and paint() sequences. However, In the methods of each, I can't understand how it is being drawn. Here are the codes.
gameUpdate()
// I will just skip the updating part because I first need to understand the background.
gameRender()
private void gameRender() {
if (DoubleBufferImage == null) {
System.out.println("The Image is null: Error occurence");
DoubleBufferImage = createImage(P_WIDTH - 15, P_HEIGHT - 15);
}
DoubleBufferGraphic = DoubleBufferImage.getGraphics();
DoubleBufferGraphic.setColor(Color.LIGHT_GRAY);
DoubleBufferGraphic.fillRect(0, 0, P_WIDTH, P_HEIGHT);
DoubleBufferGraphic.setColor(Color.BLUE);
DoubleBufferGraphic.setFont(font);
DoubleBufferGraphic.drawString("Average FPS/UPS: " +
df.format(averageFPS) + df.format(averageUPS), 10, 10);
}
paint()
public void paintScreen() {
Graphics g;
try {
g = this.getGraphics();
if ((g != null) && (DoubleBufferImage != null)) {
g.drawImage(DoubleBufferImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
} catch (Exception e) {
System.out.println("Graphics context error: " + e);
}
}
There's also paintComponent method which is overrided from Jpanel.
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (DoubleBufferImage != null) {
g.drawImage(DoubleBufferImage, 0, 0, null);
}
}
Here's my question. The running goes as update -> render -> and painting
However as you can see from the render, they used graphics to draw. But is it all drawn in DoubleBufferImage? Is Image instance similar to panel instance? I mean, is it just addable to the frame?
As this is the Double Buffering system, I want to know which methods is drawing directly, and which one is the method that draws beforehand.
Finally in the running, there is no code that it's the Image or Graphics that we made are going to be added to the panel. I just want to know the timing that the BufferedImage is being drawn.
Please help! I can't upload the whole code so I'm not sure if u guys can understand :(
Okay, so you seem to be banging against some misinformation and misunderstandings. Perhaps you should start by having a look at something like paintComponent() vs paint() and JPanel vs Canvas in a paintbrush-type GUI
In AWT/Swing there are at least two ways of performing custom painting, each with there pros and cons.
You could use paintComponent, which a "hook" into the painting system used by Swing. Swing makes use of a "passive" rendering system. This means you don't have control of when something get's painted, the paint system makes those decisions and then calls (indirectly) the paintComponent of your component so you can perform the updates.
The other mechanism (BufferStrategy) uses a "active" rendering system, which gives you complete control over when painting occurs.
As a general rule, you can't mix them. Swing has it's own painting system and won't play well with BufferStrategy, so that means if you want to use Swing components as part of your output, you can't.
But that won't answer your question, or not directly
Let's try and break it down
gameRender
private void gameRender() {
if (DoubleBufferImage == null) {
System.out.println("The Image is null: Error occurence");
DoubleBufferImage = createImage(P_WIDTH - 15, P_HEIGHT - 15);
}
DoubleBufferGraphic = DoubleBufferImage.getGraphics();
DoubleBufferGraphic.setColor(Color.LIGHT_GRAY);
DoubleBufferGraphic.fillRect(0, 0, P_WIDTH, P_HEIGHT);
DoubleBufferGraphic.setColor(Color.BLUE);
DoubleBufferGraphic.setFont(font);
DoubleBufferGraphic.drawString("Average FPS/UPS: " +
df.format(averageFPS) + df.format(averageUPS), 10, 10);
}
At this moment in time, DoubleBufferImage seems to be a BufferedImage, so when gameRender is called, it checks to see if a buffer exists and creates it as needed. It then takes a reference of the DoubleBufferImages Graphics context and prepares it for rendering, cleaning off what was previously painted to it.
A quick overview of Graphics
Graphics is an abstract layer over the top of the underlying rendering pipeline, often implement using either OpenGL or DirectX depending on the system. It provides a common layer onto which graphics operations can be performed in a system independent manner
paintScreen
public void paintScreen() {
Graphics g;
try {
g = this.getGraphics();
if ((g != null) && (DoubleBufferImage != null)) {
g.drawImage(DoubleBufferImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync();
} catch (Exception e) {
System.out.println("Graphics context error: " + e);
}
}
This worries me, as I have no context, but this.getGraphics() seems to be taking a reference of a component's Graphics context and drawing the DoubleBufferImage to it.
This is dangerous and ill advised. getGraphics returns a snapshot of the component from when it was last painted, which could be painted over at anytime when the component is painted again.
You should, at the earliest opportunity, get rid of this method.
paintComponent
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (DoubleBufferImage != null) {
g.drawImage(DoubleBufferImage, 0, 0, null);
}
}
As mentioned above, paintComponent is the preferred method for hooking into the paint system of Swing. All this does is paints the DoubleBufferImage it, although it should actually read g.drawImage(DoubleBufferImage, 0, 0, this);
So, what is all this doing?
Basically, it's an ill-advised attempt to perform double buffering in Swing ... which is already double buffered by default.
However as you can see from the render, they used graphics to draw. But is it all drawn in DoubleBufferImage? Is Image instance similar to panel instance?
No. A component is an object, which has a number of properties. One of it's jobs is to paint it's state, which is done via the various paint methods, which is passed a Graphics context which is attached to a native peer and eventually will be rendered to the screen (or printer).
A BufferedImage is just that, an image. The Graphics context is just a simple means by which you can paint to it. It can then be saved to a file or, as is the case here, painted to a component (via it's Graphics) context.
As I said above, Graphics is just an abstract layer, which allows you to perform painting operations to a number of different destinations, screen, printers, images, etc...
I mean, is it just addable to the frame?
No. It's not a component based class
As this is the Double Buffering system, I want to know which methods is drawing directly, and which one is the method that draws beforehand.
paintComponent and (the ill-advised) paintScreen are painting the image directly to the component, which will, eventually be rendered to the screen by the painting sub system.
Further reading...
Performing Custom Painting
Painting in AWT and Swing
Passive vs. Active Rendering
BufferStrategy and BufferCapabilities
I'm creating a java implantation of http://alteredqualia.com/visualization/evolve/, as a hobby project. I'm using HW-accelerated Graphics2D to draw the polygons on a bufferedImage, which works, but the calling of fillPolygon() so many times cripples the application in terms of speed.
So now my question is: Is there any way to speed up this process?
private BufferedImage createImage() //Gets called once
{
BufferedImage bImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
bImage.setAccelerationPriority(1);
Graphics2D g2d = (Graphics2D) bImage.getGraphics();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(
RenderingHints.KEY_COLOR_RENDERING,
RenderingHints.VALUE_COLOR_RENDER_SPEED);
this.g2d = g2d;
return bImage;
}
private void reDraw() //Gets called every frame
{
drawBackground(g2d);
for(int i = 0; i < polygonList.getLength(); i++)
{
polygonList.get(i).draw(g2d);
}
}
public void draw(Graphics2D g2d)
{
if(rgba[3] != 0f)
{
g2d.setColor(new Color(rgba[0], rgba[1], rgba[2], rgba[3]));
g2d.fillPolygon(this);
}
}
With the use of java.awt.Graphics there is not much you can do on your end to improve performance except the usual optimizations of Java (reducing object creation and function calls etc). You can however choose how it renders on its end with the RenderHints as I see you are doing; I would suggest you set all the hints to speed including disabling antialiasing because that is actually one of the biggest hits.
Apart from that I can see you are using some array of what I can assume are ints and creating a colour with them, now I'm not sure what class this is from (assuming it's all from one class, please correct me) - nethertheless the if statement could be a return instead (that wont help much), and you should cache this Colour when it changes, I suggest not using the rgba array and using one global Color instance and then use getRed/Green/Blue if you ever need them.
If you would like more advice you can move this to Code Review
Hope this question could emphasize more about the fading out effect of Jlabel (swing).
Certainly, yes... I already follow some guide and some answers given from This Link Thread, but mine is quite a bit different. It's not just only A text inside the JLabel, there's an image i put on.
I proceed to follow on the Thread Located out of stackoverflow. And yet, it gives me a fade out effect. But there's horrible thing occured; the white background.
How to solve this out?
I share the interface here...
The First screenshot taken here is the earlier phase when the fade out have not occured yet. While,
The Second screenshot taken here is the unwanted result i mentioned.
Tobe honest, I used the Trident Library to do animatiing;
So, whenever the user click over the image it will execute this code;
Timeline tm = new Timeline(jll_btnProceed);
tm.addPropertyToInterpolate("intensity", 1.0f, 0.0f);
tm.setDuration(1000);
tm.play();
and... the JLabel itself, I used to override it using this source code;
/**
*
* #author Gumuruh
*/
public class JLabelFader extends JLabel {
private float intensity = 1.0f;
public void setIntensity(float intensity) {
this.intensity = intensity;
this.setOpaque(false);
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
final Composite oldComposite = g2.getComposite();
g2.setComposite(AlphaComposite.SrcOver);
final Color c = getBackground();
final Color color = new Color(c.getRed(), c.getGreen(), c.getBlue(), (int) (255 * (1.0f - intensity)));
g2.setColor(color);
g2.fillRect(0, 0, getWidth(), getHeight());
g2.setComposite(oldComposite);
}
}
My hand and my head can't stop for making this trully solved. Thus I tried to follow up some example from the Java Filthy Rich Client ebook and then applying the source code given below, but first I need to COMMENT the protected void paint(Graphic g) method written above, and simply adding this source code;
private BufferedImage buttonImage = null;
public void paint(Graphics g) {
// Create an image for the button graphics if necessary
if (buttonImage == null || buttonImage.getWidth() != getWidth()
|| buttonImage.getHeight() != getHeight()) {
buttonImage = getGraphicsConfiguration().
createCompatibleImage(getWidth(), getHeight());
}
Graphics gButton = buttonImage.getGraphics();
gButton.setClip(g.getClip());
// Have the superclass render the button for us
super.paint(gButton);
// Make the graphics object sent to this paint() method translucent
Graphics2D g2d = (Graphics2D) g;
AlphaComposite newComposite =
AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity);
g2d.setComposite(newComposite);
// Copy the button's image to the destination graphics, translucently
g2d.drawImage(buttonImage, 0, 0, null);
}
in which at the end... giving me nice fade out effect. But At first, it gave me the 2nd horrible effect which is BLACK BACKGROUND rendered first. Can't believe me?? Okay, Here is First screen shot AFTER applying code from ebook. and here is the nice fade out effect result.
If there's somebody telling me;
"YOUR PNG IS NOT TRANSPARENT!".
Please, dont say like that. Because, I followed the creation of PNG inside the Photoshop nicely using this Tut.
Now, My head's spinned, but my heart laughed and can't handle it over. OMG. Geeezzz....!
And the New Stories begun...
* UPDATED FROM HERE AND BELOW *
Ehm, depply thank you very much to our friend called... MKorbel,
from his thread given at this link. Providing a clear example of fading out effect the Swing JButton and I tried to implement it into my JLabel, and violaaa...!!
IT works.
Let's give a big clap for MKorbel. :D
SO anyway, how could I fix the earlier code? Pretty simple, just COMMENT the Paint() method, and use again the paintComponent() method and it should be overriden with the new source code below;
#Override
public void paintComponent(java.awt.Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, intensity));
if (rectangularLAF && isBackgroundSet()) {
Color c = getBackground();
g2.setColor(c);
g.fillRect(0, 0, getWidth(), getHeight());
}
super.paintComponent(g2);
g2.dispose();
}
Now the JLabel become easy to be changed with its intensity -variable.
Fading out and Fading in is accomplished.
Okay. Now everything seems "OKAY". BUt hold a moment, there's something strangely occured again here. Have you noticed it? Hmmm....
I tried to give a Mouse Event (Hover On) into the JLabel that we override the paintComponent() method discussed earlier.With this line of code;
myJLabel.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
Logically, it should change the Cursor when Hover ON. But, Here comes another strange effect. (Really sorry, but this is stil the continue of the main case). The strange effect now is the Mouse Cursor can't be changed when we Hover On the Jlabel. It still can't change the Cursor. Seems the paintComponent() method effecting the way Cursor react. Is that true?
I have made a custom component (derived from JComponent) which represents
a draggable Bezier-curve.
(looks like a hanging cable, someone might know it
from Bender or Cubase)
My problem is: The curve may become really long,
let's say from top left to bottom right corners of the desktop.
This makes Swing's repaint functionality inefficient:
The area of the curve is perhaps few hundred pixels, but the area of
the component (being mostly 'transparent') is millions of pixels big.
My subjection impression is:
The longer the curve, the more flicker I get when dragging it.
I hope I made myself clear about the problem.
Perhaps it would help when I somehow could choose by myself, which regions
of the component needs repainting at all.
EDIT:
Such a mess! I'm profiling the application using Netbeans, which helps to
find inefficient code normally, but this Swing framework is making hundreds
of nested calls! I just can't figure out, what is slow and why.
By the way, disabling super.paint(...) or super.paintComponent(...) doesn't help.
Check out Filthy Rich Clients by Chet Haase and Romain Guy. They address these very optimizations among others along the way to producing responsive and graphically impressive UI.
Doing all of your bezier mathematics on the paint thread everytime the component is refreshed is (as you've gathered) a bad idea. Does your curve change often? If not then why not paint it to a BufferedImage as and when it changes, and change your paint() code to simply draw the buffered image to the component instead.
class CurveComponent extends JComponent {
private BufferedImage image;
#Override
public void paintComponent( Graphics g ) {
if ( image == null ) {
return;
}
g.drawImage( image, 0, 0, this );
}
private void updateCurve() {
image = new BufferedImage( getWidth(), getHeight(), BufferedImage.ARGB );
Graphics g = image.getGraphics();
// draw the curve onto image using g.
g.dispose();
}
}
Only call updateCurve() when you need to and all that expensive mathematics won't be needlessly repeated. Painting should be pretty responsive, even for a fullscreen window. drawImage() will be doing a straightforward memory copy and should be lightning fast.
Try writing a tiny test app, which consists of nothing except what you need to reproduce this problem. This will make profiling easier. Then post that app here, so we can take a look at possible solutions.
I found your question interesting so I wrote a test app myself. This draws a Bezier curve which is continually resized as you drag. I created a gradient background to ensure this works well with a nasty background. I get good performance and low flicker, although I use top-notch machine.
It pays to read "Filthy Rich Clients" to learn all the tricks of writing custom Swing components that perform really well.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.CubicCurve2D;
import java.awt.geom.Point2D;
public class CustomComponent extends JComponent {
private Point2D start = new Point2D.Double(0, 0);
private Point2D end = new Point2D.Double(300, 200);
private CustomComponent() {
this.setOpaque(true);
final MouseAdapter mouseAdapter = new MouseAdapter() {
#Override
public void mouseDragged(MouseEvent e) {
setEnd(e.getPoint());
}
};
this.addMouseListener(mouseAdapter);
this.addMouseMotionListener(mouseAdapter);
}
public void setStart(Point2D start) {
this.start = start;
repaint();
}
public void setEnd(Point2D end) {
this.end = end;
repaint();
}
#Override
protected void paintComponent(Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
// draw gradient background
final int width = getWidth();
final int height = getHeight();
g2.setPaint(new GradientPaint(0, 0, Color.WHITE, width, height, Color.YELLOW));
g2.fillRect(0, 0, width, height);
// draw Bezier curve
final Shape shape = new CubicCurve2D.Double(start.getX(), start.getY(), start.getX(), end.getY(), end.getX(), start.getY(), end.getX(), end.getY());
g2.setColor(Color.BLACK);
g2.draw(shape);
g2.drawString("Click and drag to test for flickering", 100, 20);
}
public static void main(String[] args) {
final CustomComponent component = new CustomComponent();
final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
final Dimension size = new Dimension(screenSize.width - 20, screenSize.height - 100);
component.setPreferredSize(size);
final JFrame frame = new JFrame();
frame.add(component);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Some things to note:
only overwrite paintComponent(Graphics g), not the other paintXXX() methods
set custom component to opaque if possible
only use repaint() to request repainting. Never directly order a repaint directly in your code. This lets Swing handle it well.
There is no efficient way to create lots of small clip rectangles for a diagonal structure which leaves you with two strategies to avoid flickering:
Double buffering. This needs an enormous amount of memory but the memory copy is very fast (it usually happens in the time the "electron beam" goes back from lower right to upper left ... if there was still a beam in your LCD).
Don't call super.paint() (which draws or "erases" the background) and draw the curve a second time with the background color to erase it.
For more details, see this document.
[EDIT] If fillRect() wasn't abstract, you could set a break point :) Set a break point in paint(), check who calls it and whether the background got cleared at that time. It should be since rendering would be completely wrong. Then set break points further up in the call chain.
You can redraw a smaller portion of the screen using repaint(Rectangle r)
http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html#repaint(java.awt.Rectangle)
Then you mention flicker. Since you are using swing, which uses double buffering your flickering must be coming from something else. Are you clearing the screen in paintComponent(...)? I.e. call to fillRect(...)? Don't do that, it's not needed (IIRC).
Which method do yo use to paint your curve? paint or paintComponent?
My solution was a partial re-design:
Now I don't represent each "cable"-element by a component.
Now, cables are just dummy objects (with no involved JComponent).
The repaint takes place "globally", on the content pane of the parent JFrame.
Now it's efficient, and flickers less.
just use getVisibleRect(); inside paintComponent(Graphics g) to get the area you actually need to redraw