1

I am new to java and now like to make an application for drawing images and capturing it through JPanel. I tried a lot but failed. The code I used is given below. Please help Thanks in advance. The program draws images by dragging the mouse. And type a character in the textbox provided the press scan

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

    }  
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319
  • You mentioned that you tried a lot. But it would be very convenient for us to know what have you tried? Also please mention that if you got any errors.. etc..? – ρss Feb 24 '14 at 19:23
  • See [this answer](http://stackoverflow.com/a/5853992/418556) for tips. – Andrew Thompson Feb 24 '14 at 22:56
  • And [this](https://stackoverflow.com/questions/21995995/unable-take-screenshot-of-jframe-java-swing/21998201#21998201) example – MadProgrammer Feb 25 '14 at 00:55

1 Answers1

1

I would suggest only drawing to your buffered image at the time you draw on the panel.

So you could remove your whole paintComponent(...) method, change your mouse drag listener to this:

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

And then change your scan method to this:

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();
    }
}
Nick Rippe
  • 6,465
  • 14
  • 30