我正在尝试创建某种Paint程序。我创建了一个BufferedImage和一个Graphics2D,但我不能用它。所有我能看到的是BufferedImage本身没有任何变化。
public class paintapp implements ActionListener, MouseListener, MouseMotionListener
{
public static final int WIDTHBUFF=300;
public static final int HEIGHTBUFF=300;
BufferedImage buffimage=new BufferedImage(WIDTHBUFF,HEIGHTBUFF,BufferedImage.TYPE_INT_BGR);
JLabel imagelabel=new JLabel(new ImageIcon(buffimage));
int s=3;
Color curr_color=Color.BLACK;
int x,y;
public static final int WIDTH=700;
public static final int HEIGHT=700;
public paintapp()
{
Graphics2D g2d=buffimage.createGraphics();
g2d.setBackground(Color.WHITE);
g2d.fillRect(0, 0, WIDTHBUFF,HEIGHTBUFF);
JFrame frame=new JFrame("Painter");
frame.setSize(WIDTH, HEIGHT);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.setVisible(true);
Panel buttonpanel=new Panel();
Panel colors=new Panel();
Panel draw=new Panel();
draw.add(imagelabel);
frame.add(draw);
frame.pack();
}
public static void main(String[]args)
{
paintapp paint1=new paintapp();
}
@Override
public void mouseDragged(MouseEvent e) {
Graphics2D g2=buffimage.createGraphics();
g2.setColor(curr_color);
g2.setStroke(new BasicStroke(s));
g2.drawLine(x, y, e.getX(), e.getY());
x=e.getX();
y=e.getY();
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
x=e.getX();
y=e.getY();
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:0)
我看到你正在偷偷摸摸地把事情弄得乱七八糟。如果您阅读指南,您将看到情况如何。
第一个主要的事情是将MouseMotionListener添加到绘图中 - 就像JLabel JPanel一样。
第二件事是,一旦你走出构造函数之外,JFrame就会丢失(除非你做了一些奇特的事情)并且无法访问以刷新,所以系统决定何时刷新,你会看到 - 在你添加之后鼠标监听器 - 一旦隐藏并再次显示绘图窗口,您的绘图就会出现。
所以你需要将JFrame作为全局 - 为什么你没有让你扩展JFrame类,所以不需要额外的JFrame。