Drawing Graphics is too slow

 

Questions


So, I have this project, and you can draw images in it. I wanted people to be able to draw on it, but at first it was too slow when I was using repaint() So i used the repaint(Rectangle r) tool. It’s better, but still not the speed i was looking for.
Here is the code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;


public class DrawingPad extends JPanel implements MouseListener,MouseMotionListener,ListSelectionListener{
public Color[][] picture = new Color[601][601];
public Color selected;
public String action;
public Maker m;
private static final long serialVersionUID = 1L;
public DrawingPad(Maker m){
    this.m = m;
    this.setPreferredSize(new Dimension(600,600));
    this.setVisible(true);
    for (int x = 1;x<=600;x++){
        for (int y = 1; y<=600;y++){
            picture[x][y]=Color.WHITE;
        }
    }
}
public void addColor(int x, int y){
    try{
        picture[x][y]=selected;
        repaint(new Rectangle(x,y,x,y));
    }catch (Exception e){

    }
}
@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    g.clearRect(0, 0, 600, 600);
    for (int x = 1;x<=600;x++){
        for (int y = 1; y<=600;y++){
            g.setColor(picture[x][y]);
            g.drawLine(x, y, x, y);
        }
    }
}
@Override
public void mouseClicked(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseEntered(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseExited(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mousePressed(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseReleased(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void mouseDragged(MouseEvent e) {
    for (int x = -1;x<=1;x++){
        for (int y = -1;y<=1;y++){
            this.addColor(e.getX()+x, e.getY()+y);
        }   
    }
}
@Override
public void mouseMoved(MouseEvent arg0) {
    // TODO Auto-generated method stub

}
@Override
public void valueChanged(ListSelectionEvent e) {
    if (e.getSource()==m.seeit){
        selected = m.colors[m.seeit.getSelectedIndex()];
    }else{
        action=(String) m.actions.getSelectedValue();
    }

}
}

 

 

————————————————-

Answer

You might want to look into drawing that which will not be changed into a BufferedImage, and then displaying that BufferedImage in the paintComponent method as a background image.

For example, please have a look at this link and also this one.

bufferedimage,graphics,java,paintcomponent,swing

Facebook Comments

Post a comment