绘制图形速度太慢

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

}
}

你说它慢是什么意思?绘制时是否闪烁?看一下双缓冲技术:http://docs.oracle.com/javase/tutorial/extra/fullscreen/doublebuf.html - JScoobyCed
它不会闪烁,我解决了那个问题。 - Barakados
3
为了更快地获得帮助,请发布一个SSCCE。请注意,SSCCE是指提供最小化、自我包含的代码示例,以便他人能够重现和解决您的问题。 - Andrew Thompson
请注意,您的 paintComponent() 实现具有 O(n ^ 2) 复杂度,其中 n = 601。 - trashgod
1个回答

5
你可能需要考虑将不会更改的内容绘制到 BufferedImage 中,然后在 paintComponent 方法中显示该 BufferedImage 作为背景图像。
例如,请参阅 此链接这个链接

1
@javawarrior 你可能会喜欢阅读一下《AWT和Swing中的绘图》(http://www.oracle.com/technetwork/java/painting-140037.html),作为解释为什么你的解决方案如此缓慢的入门指南。 - MadProgrammer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接