Quick actions

cmd+k|ctrl+k

Navigation

Languages

Simpan Gambar Java Swing

Snippet info

Language

Java

Visibility

public

Author

riyanto.droider

Created

2025-06-25T05:29:49.402975Z

Updated

2025-06-26T04:34:46.232911Z

// letakkan kedua variabel ini pada scope yg dapat diakses dari method manapun
String fileName;
String filePath;

// ketika memilih file
private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {                                     
    // membuat objek file chooser
    JFileChooser fileChooser = new JFileChooser();
    
    // tambahkan filter hanya file gambar saja (JPG, PNG)
    fileChooser.setFileFilter(new FileNameExtensionFilter(
        "Pilih file gambar", "jpg", "png")
    );
    
    // matikan opsi all files
    fileChooser.setAcceptAllFileFilterUsed(false);
    
    // membuka dialog open file
    int option = fileChooser.showOpenDialog(this);
    
    // jika sudah memilih file lalu open
    if(option == JFileChooser.APPROVE_OPTION) {
        //fileName = fileChooser.getSelectedFile().getName();
        filePath = fileChooser.getSelectedFile().getAbsolutePath();
        
        // tampilkan gambar yang dipilih ke label
        jLabel1.setIcon(new ImageIcon(filePath));
    }
}                                    

// ketika button simpan diklik
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    try {
        // membuka koneksi ke database 'test'
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", "root", "");
        
        // perintah simpan ke tabel
        String sql = "INSERT INTO upload (file_path) VALUES ('"+ filePath +"')";
        Statement stmt = conn.createStatement();
        
        // jalankan perintah simpan
        stmt.execute(sql);
        
    } catch (SQLException ex) {
        Logger.getLogger(BukuFrame.class.getName()).log(Level.SEVERE, null, ex);
    }
} 
INFO