2012-11-16 46 views
3

所以,我有這個項目,你可以在其中繪製圖像。我希望人們能夠利用它,但起初它太慢,當我使用repaint()所以我用repaint(Rectangle r)工具。這更好,但仍然不是我想要的速度。 下面是代碼:繪圖圖形太慢

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

} 
} 
+0

你是什麼意思它很慢?它吸引時閃爍嗎?看看雙緩衝http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html – JScoobyCed

+0

它不閃爍,我解決了這個問題。 – Barakados

+3

爲了儘快提供更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –

回答

5

你可能要考慮繪製,不會變成一個BufferedImage,然後在paintComponent方法裏面作爲背景圖像顯示的是BufferedImage的。

例如,請查看this link以及this one

+0

我該怎麼做? – Barakados

+0

@javawarrior:請參閱編輯指向代碼示例的鏈接。 –

+1

@javawarrior您可能希望閱讀[AWT和Swing中的繪圖](http://www.oracle.com/technetwork/java/painting-140037.html),作爲解答爲什麼如此緩慢 – MadProgrammer