30/09/2018, 20:26

Làm sao để lưu các paint đã vẽ trên jPanel ghi gọi hàm repaint()

Chả là em đang làm 1 cái tool paint bằng java swing lúc paint trên jpanel thì vẫn binh thường nhưng nếu mình vẽ tiep 1 hình khác thì hình trước sẽ bị mất … em có dùng hàm repaint để bắt sự kiện theo chuột ạ … vấn đề ở đây là hàm repaint nó sẽ clear tất cả rồi mới paint cái mới lên vậy làm sao để em save nó lại a ?

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author s
 */
public class MainFrame extends JFrame {

    /**
     * Creates new form MainFrame
     */
    String shapess = "";
    Color currentcolor = Color.BLACK;
    int sizee = 1;
    
    Point p1 = new Point(0, 0);
     Point p2 = new Point(0, 0);
 BufferedImage savingpaint =null;
    public MainFrame() {
        initComponents();
      savingpaint = new BufferedImage(DrawPanel.getWidth(),DrawPanel.getHeight(),BufferedImage.TYPE_3BYTE_BGR);
    }
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        DrawPanel = new javax.swing.JPanel();
        main = new javax.swing.JMenuBar();
        file = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        save = new javax.swing.JMenuItem();
        neww = new javax.swing.JMenuItem();
        shapes = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();
        rec = new javax.swing.JMenuItem();
        jMenuItem3 = new javax.swing.JMenuItem();
        jMenuItem4 = new javax.swing.JMenuItem();
        draw = new javax.swing.JMenuItem();
        color = new javax.swing.JMenu();
        colorpick = new javax.swing.JMenuItem();
        size = new javax.swing.JMenu();
        onepix = new javax.swing.JMenuItem();
        threepx = new javax.swing.JMenuItem();
        fivepixel = new javax.swing.JMenuItem();
        eightpix = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Paint");

        DrawPanel.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                DrawPanelMouseDragged(evt);
            }
        });
        DrawPanel.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                DrawPanelMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                DrawPanelMouseReleased(evt);
            }
        });

        javax.swing.GroupLayout DrawPanelLayout = new javax.swing.GroupLayout(DrawPanel);
        DrawPanel.setLayout(DrawPanelLayout);
        DrawPanelLayout.setHorizontalGroup(
            DrawPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 1292, Short.MAX_VALUE)
        );
        DrawPanelLayout.setVerticalGroup(
            DrawPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 763, Short.MAX_VALUE)
        );

        main.setAlignmentX(1.0F);
        main.setAlignmentY(1.0F);
        main.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
            public void mouseDragged(java.awt.event.MouseEvent evt) {
                mainMouseDragged(evt);
            }
        });

        file.setText("File");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Open");
        file.add(jMenuItem1);

        save.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        save.setText("Save");
        file.add(save);

        neww.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.CTRL_MASK));
        neww.setText("New");
        file.add(neww);

        main.add(file);

        shapes.setText("Shapes");

        jMenuItem2.setText("Line");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        shapes.add(jMenuItem2);

        rec.setText("Rectangle");
        rec.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                recActionPerformed(evt);
            }
        });
        shapes.add(rec);

        jMenuItem3.setText("Oval");
        jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem3ActionPerformed(evt);
            }
        });
        shapes.add(jMenuItem3);

        jMenuItem4.setText("Rounded rectangle");
        jMenuItem4.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jMenuItem4MouseReleased(evt);
            }
        });
        jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem4ActionPerformed(evt);
            }
        });
        shapes.add(jMenuItem4);

        draw.setText("Draw");
        draw.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                drawActionPerformed(evt);
            }
        });
        shapes.add(draw);

        main.add(shapes);

        color.setText("Colors");

        colorpick.setText("Color Picker...");
        colorpick.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                colorpickActionPerformed(evt);
            }
        });
        color.add(colorpick);

        main.add(color);

        size.setText("Size");

        onepix.setText("1px");
        onepix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onepixActionPerformed(evt);
            }
        });
        size.add(onepix);

        threepx.setText("3px");
        threepx.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                threepxActionPerformed(evt);
            }
        });
        size.add(threepx);

        fivepixel.setText("5px");
        fivepixel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fivepixelActionPerformed(evt);
            }
        });
        size.add(fivepixel);

        eightpix.setText("8px");
        eightpix.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                eightpixActionPerformed(evt);
            }
        });
        size.add(eightpix);

        main.add(size);

        setJMenuBar(main);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(DrawPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(DrawPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void onepixActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
        sizee = 1;
    }                                      

    private void threepxActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        sizee = 3;
    }                                       

    private void fivepixelActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        sizee = 5;
    }                                         

    private void eightpixActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        sizee = 8;
    }                                        

    private void colorpickActionPerformed(java.awt.event.ActionEvent evt) {                                          
        // TODO add your handling code here:
        Color pickcolor = JColorChooser.showDialog(this, "Choose Color", null);
        currentcolor = pickcolor;

    }                                         

    private void DrawPanelMousePressed(java.awt.event.MouseEvent evt) {                                       
        // TODO add your handling code here:
        p1 = p2 = evt.getPoint();
        repaint();
        

    }                                      

    private void DrawPanelMouseReleased(java.awt.event.MouseEvent evt) {                                        
        // TODO add your handling code here:
        p2 = evt.getPoint();
        repaint();
        Graphics2D gg = (Graphics2D) DrawPanel.getGraphics();
        repaint();
    }                                       


    private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        shapess = "line";
    }                                          

    private void recActionPerformed(java.awt.event.ActionEvent evt) {                                    
        // TODO add your handling code here:
        shapess = "rec";
    }                                   

    private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        shapess = "oval";
    }                                          

    private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        // TODO add your handling code here:
        shapess = "roundrec";
    }                                          

    private void jMenuItem4MouseReleased(java.awt.event.MouseEvent evt) {                                         
        // TODO add your handling code here:
    }                                        

    private void drawActionPerformed(java.awt.event.ActionEvent evt) {                                     
        // TODO add your handling code here:
        shapess = "draw";
    }                                    

    private void mainMouseDragged(java.awt.event.MouseEvent evt) {                                  
        // TODO add your handling code here:

    }                                 

    private void DrawPanelMouseDragged(java.awt.event.MouseEvent evt) {                                       
        p2 = evt.getPoint();
        repaint();

    }                                      

   
   
    @Override
    public void paint(Graphics grphcs) {
        super.paint(grphcs);
        Graphics2D g = (Graphics2D) grphcs;
        g.setStroke(new BasicStroke(sizee));
        g.setColor(currentcolor);
        int leftx = 0, lefty = 0;
        int width = 0, height = 0;
        if (!p1.equals(p2)) {
            if (shapess.equals("line")) {

                g.drawLine(p1.x, p1.y, p2.x, p2.y);
                
            } else if (shapess.equals("oval")) {

                if (p1.x < p2.x) {
                    leftx = p1.x;
                } else {
                    leftx = p2.x;
                }
                if (p1.y < p2.y) {
                    lefty = p1.y;
                } else {
                    lefty = p2.y;
                }
                width = Math.abs(p1.x - p2.x);
                height = Math.abs(p1.y - p2.y);
                g.drawOval(leftx, lefty, width, height);
              

            } else if (shapess.equals("rec")) {

                if (p1.x < p2.x) {
                    leftx = p1.x;
                } else {
                    leftx = p2.x;
                }
                if (p1.y < p2.y) {
                    lefty = p1.y;
                } else {
                    lefty = p2.y;
                }
                width = Math.abs(p1.x - p2.x);
                height = Math.abs(p1.y - p2.y);
                g.drawRect(leftx, lefty, width, height);
                

            } else if (shapess.equals("roundrec")) {

                if (p1.x < p2.x) {
                    leftx = p1.x;
                } else {
                    leftx = p2.x;
                }
                if (p1.y < p2.y) {
                    lefty = p1.y;
                } else {
                    lefty = p2.y;
                }
                width = Math.abs(p1.x - p2.x);
                height = Math.abs(p1.y - p2.y);
                g.drawRoundRect(leftx, lefty, width, height, 20, 20);
               

            }
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JPanel DrawPanel;
    private javax.swing.JMenu color;
    private javax.swing.JMenuItem colorpick;
    private javax.swing.JMenuItem draw;
    private javax.swing.JMenuItem eightpix;
    private javax.swing.JMenu file;
    private javax.swing.JMenuItem fivepixel;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JMenuItem jMenuItem3;
    private javax.swing.JMenuItem jMenuItem4;
    private javax.swing.JMenuBar main;
    private javax.swing.JMenuItem neww;
    private javax.swing.JMenuItem onepix;
    private javax.swing.JMenuItem rec;
    private javax.swing.JMenuItem save;
    private javax.swing.JMenu shapes;
    private javax.swing.JMenu size;
    private javax.swing.JMenuItem threepx;
    // End of variables declaration                   
}
Vu Van Chung viết 22:30 ngày 30/09/2018

bạn thử bỏ cái super() trong hàm paint() thử xem có được không nhé!

Pis Kaël viết 22:39 ngày 30/09/2018

Bạn lưu nó lên Bitmap (Bên Java có không nhỉ) mình làm bên C#

Bài liên quan
0