下面,您可以看到我的代码的缩短版本,其中有一个错误。我正在开发一个类似于 MS Paint 的程序。问题是,当我想绘制一个矩形时,我想看看绘制的矩形实际上是什么样子的,那么直到最终的所有先前的矩形都是由程序绘制的。然后,如果查看代码的注释部分并稍作更改使用它们(不使用以前的代码),那么它会按照我希望的方式工作。但是,程序必须将图片保存到 PC 的内存中,我不希望它以这种方式工作。我是 JAVA 的初学者,我绝对不知道错误可能出在哪里,因为该方法drawImage
需要 Image 类型,而这正是我正在做的。
希望你能明白我在说什么。如果碰巧不能,复制代码并尝试一下很容易。当您尝试绘制第一个对象时,您会看到错误。
一级:
import java.awt.BorderLayout;
import javax.swing.JFrame;
public class MyPaint extends JFrame{
private Desk paintDesk;
public static void main(String[] args) {
@SuppressWarnings("unused")
MyPaint frame = new MyPaint();
}
MyPaint()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(400, 100, 600, 600);
setResizable(false);
setLayout(new BorderLayout());
paintDesk = new Desk();
this.getContentPane().add(paintDesk,BorderLayout.CENTER);
setVisible(true);
}
}
二等:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.RenderedImage;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
public class Desk extends JComponent{
private Image paintedImage;
private Image newImage;
private Graphics2D graphics;
private Point a;
private Point b;
public Desk()
{
a= new Point();
b= new Point();
setDoubleBuffered(false);
addMouseListener(new MouseAdapter(){
public void mousePressed(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e))
{
/*try {
ImageIO.write((RenderedImage)paintedImage, "JPG", new File("actual.jpg"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
newImage= paintedImage;
a.x = e.getX();
a.y = e.getY();
}
}
});
addMouseMotionListener(new MouseMotionAdapter(){
public void mouseDragged(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e))
{
/*try {
newImage= (ImageIO.read(new File("actual.jpg")));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
if(newImage!=null)
{
graphics.drawImage(newImage,0,0,null);
repaint();
}
b.x = e.getX();
b.y = e.getY();
if(graphics != null)
{
drawRect();
}
repaint();
}
}
});
addMouseListener(new MouseAdapter(){
public void mouseReleased(MouseEvent e){
if(SwingUtilities.isLeftMouseButton(e))
{
b.x = e.getX();
b.y = e.getY();
if(graphics != null)
{
drawRect();
}
repaint();
}
}
});
}
public void paintComponent(Graphics g){
if(paintedImage == null)
{
paintedImage = createImage(getSize().width, getSize().height);
graphics = (Graphics2D)paintedImage.getGraphics();
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics.setStroke(new BasicStroke(3, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND));
clear();
}
g.drawImage(paintedImage, 0, 0, null);
}
private void clear()
{
graphics.setPaint(Color.white);
graphics.fillRect(0, 0, getSize().width, getSize().height);
graphics.setPaint(Color.red);
repaint();
}
private void drawRect()
{
graphics.drawLine(a.x, a.y, b.x, a.y);
graphics.drawLine(a.x, a.y, a.x, b.y);
graphics.drawLine(a.x, b.y, b.x, b.y);
graphics.drawLine(b.x, a.y, b.x, b.y);
}
}