3

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();
    }

}
}
CAMOBAP
  • 5,523
  • 8
  • 58
  • 93
Barakados
  • 371
  • 7
  • 19

1 Answers1

5

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.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    @javawarrior You might like to have a read through [Painting in AWT and Swing](http://www.oracle.com/technetwork/java/painting-140037.html) as a primer to why your solution was so slow – MadProgrammer Nov 16 '12 at 02:05