捕获/保存JPanel图像

时间:2014-02-24 19:04:45

标签: java swing jpanel bufferedimage mouse-listeners

我是java的新手,现在想制作一个应用程序来绘制图像并通过JPanel捕获它。我尝试了很多但失败了。我使用的代码如下。请帮忙 提前致谢。 程序通过拖动鼠标绘制图像。如果按下扫描,则在文本框中键入一个字符

import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class SwingPaintDemo3 {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                createAndShowGUI(); 
            }
        });
    }

    private static void createAndShowGUI() {

        final JFrame f = new JFrame("Swing Paint Demo");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
        f.setLayout(null);
        f.setBounds(0,0,800,600);
        JButton scanButton=new JButton("Scan");
        scanButton.setBounds(0,0,75, 40);
        f.add(scanButton);
        JButton eraseButton=new JButton("Erase");
        eraseButton.setBounds(0,50,75, 40);
        f.add(eraseButton);
        JLabel label1=new JLabel("Program developed by Gopakumar in connection with MCA project MCP 60");
        label1.setBounds(0, 500, 600,50);
        f.add(label1);
        final JTextField textBox=new JTextField();
        textBox.setBounds(510, 50,50,50);
        f.add(textBox);
        Font font=new Font(Font.SANS_SERIF,Font.BOLD,50);
        textBox.setFont(font);
        final JLabel label2=new JLabel("Please type the Character for training");
        label2.setBounds(505, 110, 600,50);
        f.add(label2);
        final MyPanel pan=new MyPanel();
        f.add(pan);
        f.setVisible(true);

        eraseButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {
        f.repaint();
        }
        });
        scanButton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e)
        {
        if(textBox.getDocument().getLength()<1){
            label2.setText("Please type the Character for training");
            label2.setForeground(Color.red);
        }
        else if(textBox.getDocument().getLength()>1){
            label2.setText("please Enter only one character");
        }
        else{
            label2.setForeground(Color.BLACK);
            label2.setText("Please type the Character for training");
            scan(pan);


        }
        }
        });

    } 

    private static void scan(MyPanel pan1) {
int i,j;
pan1.bi.getGraphics();
pan1.paint(pan1.gd);
// Save your screen shot with its label
File outputfile = new File("image.jpg");
    try {
        ImageIO.write(pan1.bi, "jpg", outputfile);
    } catch (IOException ex) {
        Logger.getLogger(SwingPaintDemo3.class.getName()).log(Level.SEVERE, null, ex);
    }

  }
}

 class MyPanel extends JPanel {

    private int x = 0;
    private int y = 0;
    private int ox = 0;
    private int oy = 0;
    private Graphics graphicsForDrawing;
    //private boolean dragging;
public BufferedImage bi=new BufferedImage(400,400,BufferedImage.TYPE_INT_RGB);
public Graphics gd;
    public MyPanel() {
        this.gd = bi.getGraphics();
        this.paint(gd);

        setBorder(BorderFactory.createLineBorder(Color.black));
        this.setBackground(Color.WHITE);
        this.setBounds(100, 50,400, 400);

        addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                x = e.getX();  
                y = e.getY();
                ox = x;
                oy = y;
           // dragging = true;
            setUpDrawingGraphics();
            }
        });

        addMouseMotionListener(new MouseAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                x = e.getX();   
                y = e.getY(); 
                graphicsForDrawing.drawLine(ox, oy, x, y);
                gd.drawLine(ox, oy, x, y);
                ox = x;
                oy = y;
            }
        });
        addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e){
                if(SwingUtilities.isRightMouseButton(e)){
                    clear();
                }
            }

        });

    }
    private void setUpDrawingGraphics() {
         graphicsForDrawing = getGraphics();
         graphicsForDrawing.setColor(Color.black);
         gd.setColor(Color.black);
    }

   public void clear(){
      repaint();
   }


    public Dimension getPreferredSize() {
        return new Dimension(400,300);
    }

    protected void paintComponent(Graphics g) {
        super.paintComponent(g);     
        gd.drawImage(bi,0, 0, this);

    }  
}

1 个答案:

答案 0 :(得分:0)

我建议您在面板上绘图时只绘制缓冲图像。

因此,您可以删除整个paintComponent(...)方法,将鼠标拖动侦听器更改为:

addMouseMotionListener(new MouseAdapter() {
    @Override
    public void mouseDragged(MouseEvent e) {
        x = e.getX();   
        y = e.getY(); 
        Graphics g = bi.getGraphics();
        g.setColor(Color.green);
        g.drawLine(ox, oy, x, y);
        getGraphics().drawLine(ox, oy, x, y);
        ox = x;
        oy = y;
    }
});

然后将您的scan方法更改为:

private static void scan(MyPanel pan1) {
    int i,j;
    // Save your screen shot with its label
    File outputfile = new File("image.jpg");
    try {
        ImageIO.write(pan1.bi, "jpg", outputfile);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}