简体   繁体   中英

How to draw on the JFrame?

I have a pdf file, which is rendered as an image and added as a JLabel in the JFrame. Now i want to draw on the contents in the JFrame by mouseclick and keystrokes. And these drawings should appear on the image(JLabel). I have pasted my code below. Can anyone please help me to figure it out!!!

public class LinePanel extends JPanel{

public static final String RESOURCE = "G:/resource/A0TestFile.pdf";
private MouseHandler mouseHandler = new MouseHandler();
private Point p1;
private Point p2;
private Point p3;
private Point p4;

ArrayList<Point> points = new ArrayList<Point>();
public LinePanel() {

    this.addMouseListener(mouseHandler);
    this.addMouseMotionListener(mouseHandler);
}

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setColor(Color.BLACK);
    g2d.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setStroke(new BasicStroke(1,
        BasicStroke.CAP_SQUARE, BasicStroke.JOIN_BEVEL));
       crop(g);
} 

public void crop(Graphics g){

    if(points != null && points.size()>0){

        for(int i=0;i<points.size();i++){
             p1 = points.get(i);
             g.drawLine(p1.x, p1.y, p1.x-20, p1.y);
             g.drawLine(p1.x, p1.y, p1.x, p1.y+20);
        }

        for( i=1;i<points.size();i++){
            p2 = points.get(i);
            g.drawLine(p2.x, p2.y, p2.x-20, p2.y);
            g.drawLine(p2.x, p2.y, p2.x, p2.y-20);
        }

        for( i=2;i<points.size();i++){
            p3 = points.get(i);
            g.drawLine(p3.x, p3.y, p3.x+20, p3.y);
            g.drawLine(p3.x, p3.y, p3.x, p3.y-20);
        }

        for( i=3;i<points.size();i++){
            p4 = points.get(i);
            g.drawLine(p4.x, p4.y, p4.x+20, p4.y);
            g.drawLine(p4.x, p4.y, p4.x, p4.y+20);
        } 
    }
}

private class MouseHandler extends MouseAdapter {

    @Override
    public void mousePressed(MouseEvent e) {
        if(points.size()<4){
            points.add(e.getPoint());

            repaint();

        }  
    }

    @Override
    public void mouseReleased(MouseEvent e) {

    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }
}

private class ControlPanel extends JPanel {

    private static final int DELTA = 1;

    public ControlPanel() {
        new MoveButton("\u2190", KeyEvent.VK_LEFT, -DELTA, 0);
        new MoveButton("\u2191", KeyEvent.VK_UP, 0, -DELTA);
        new MoveButton("\u2192", KeyEvent.VK_RIGHT, DELTA, 0);
        new MoveButton("\u2193", KeyEvent.VK_DOWN, 0, DELTA);
    }

    private class MoveButton extends JButton {

        KeyStroke k;
        int dx, dy;

        public MoveButton(String name, int code,
                final int dx, final int dy) {
            super(name);
            this.k = KeyStroke.getKeyStroke(code, 0);
            this.dx = dx;
            this.dy = dy;
            this.setAction(new AbstractAction(this.getText()) {

                @Override
                public void actionPerformed(ActionEvent e) {

                    if(points.size()==1){
                        LinePanel.this.p1.translate(dx, dy);
                        LinePanel.this.repaint();
                    }

                    if(points.size()==2){
                        LinePanel.this.p2.translate(dx, dy);
                        LinePanel.this.repaint();
                    }

                    if(points.size()==3){   
                        LinePanel.this.p3.translate(dx, dy);
                        LinePanel.this.repaint();
                    }

                    if(points.size()==4){ 
                        LinePanel.this.p4.translate(dx, dy);
                        LinePanel.this.repaint();
                    }
                }
            });
            ControlPanel.this.getInputMap(WHEN_IN_FOCUSED_WINDOW)
                .put(k, k.toString());
            ControlPanel.this.getActionMap()
                .put(k.toString(), new AbstractAction() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    MoveButton.this.doClick();
                }
            });
        }
    }
}

private void display() throws IOException{

    File file = new File(RESOURCE);
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    FileChannel channel = raf.getChannel();
    ByteBuffer buf = channel.map(FileChannel.MapMode.READ_WRITE,
        0, channel.size());
    PDFFile pdffile = new PDFFile(buf);

   PDFPage page = pdffile.getPage(1);

Rectangle rect = new Rectangle(0,0,(int)page.getBBox().getWidth(),(int)page.getBBox().getHeight());

Image img = page.getImage(rect.width, rect.height,rect,null,true,true); 
    JFrame f = new JFrame("LinePanel");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setPreferredSize(new Dimension(800, 800));

    JPanel panel = new JPanel();
    JLabel image = new JLabel(new ImageIcon(img));
    panel.add(image);
    JScrollPane jspane=new JScrollPane(panel);
    f.add(jspane, BorderLayout.CENTER);
    f.add(this);
    f.add(new ControlPanel(),BorderLayout.SOUTH);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

}

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {

        @Override
        public void run() {
            try {
                new LinePanel().display();
            } catch (IOException ex) {
                Logger.getLogger(LinePanel.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });
}
}

Try this. It's a Panel with an Image. Add the Panel to the Frame;

public class ImagePanel extends JPanel{

    private BufferedImage image;

        public ImagePanel() {
            try {                
                image = ImageIO.read(new File("image name and path"));
            } catch (IOException ex) {
                // handle exception...
       }
   }

   @Override
   protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);  

        // draw other stuff       
   }

}

If you want your drawing to be painted on top of any component added to the panel/frame, you need to override the paint() method.

Take a look at A Closer Look at the Paint Mechanism

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM