以下のように、描画は直接画面に行うのではなく、オフスクリーンイメージに書きこんでおいて、
それを適時画面に転送するようにすればよいでしょう。
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
class pc extends Canvas implements ActionListener {
public static final String C[] = {"0","1","2","3","4","5","6","7"};
private BufferedImage OSImage, II[];
private Graphics G;
private Color PC[];
private int X, Y;
public pc() {
OSImage = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
G = OSImage.getGraphics();
II = new BufferedImage[8];
PC = new Color[8];
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
X = e.getX() * 100 / getWidth(); Y = e.getY() * 100 / getHeight(); };
public void mouseReleased(MouseEvent e) {
G.drawLine(X, Y, e.getX() * 100 / getWidth(), Y = e.getY() * 100 / getHeight());
repaint();};
});
};
public void actionPerformed(ActionEvent ae) {
for (int i = 0; i < 8; i ++)
if (ae.getActionCommand().compareTo(C[i]) == 0) G.setColor(PC[i]);
};
public void paint(Graphics g) { g.drawImage(OSImage, 0, 0, getWidth(), getHeight(), this); };
public void update(Graphics g) { paint(g); };
public JButton CreateButton(int n) {
PC[n] = new Color((n & 1) * 0xFF + (n & 2) * 0x7F80 + (n & 4) * 0x3FC000 + 0xFF000000);
II[n] = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);
Graphics g = II[n].getGraphics();
g.setColor(PC[n]);
g.fillRect(0, 0, 16, 16);
g.dispose();
JButton b = new JButton(new ImageIcon(II[n]));
b.addActionListener(this);
b.setActionCommand(C[n]);
return(b);
};
}
public class painter {
public static void main(String args[]) {
int i;
JFrame MF = new JFrame("LineWriter");
MF.setSize(640, 480);
pc PC = new pc();
MF.getContentPane().add(PC, BorderLayout.CENTER);
JToolBar TB = new JToolBar();
for (i = 0; i < 8; i ++) TB.add(PC.CreateButton(i));
MF.getContentPane().add(TB, BorderLayout.NORTH);
MF.setVisible(true);
};
}