Skip to content

Instantly share code, notes, and snippets.

@fanjavaid
Created February 27, 2013 07:11
Show Gist options
  • Save fanjavaid/5045871 to your computer and use it in GitHub Desktop.
Save fanjavaid/5045871 to your computer and use it in GitHub Desktop.
Menampilkan data yang bersesuain di JComboBox
/**
*
* @author akhmad
*/
public class Application extends javax.swing.JFrame {
private Connection connection;
/**
* Creates new form Application
*/
public Application() {
try {
initComponents();
cmbNama.addActionListener(new ComboBoxListener());
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_case", "root", "3092");
ambilData(connection);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException se) {
Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, se);
}
}
public void ambilData(Connection conn) throws SQLException{
String query = "SELECT * FROM tb_barang";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
List<Barang> list = new ArrayList<>();
cmbNama.removeAllItems();
while (rs.next()) {
Barang barang = new Barang();
barang.setId(rs.getInt("id"));
barang.setNama(rs.getString("nama"));
barang.setHarga(rs.getInt("harga"));
list.add(barang);
}
// Tampilkan data ke combobox
DefaultComboBoxModel model = new DefaultComboBoxModel();
for (Barang brg : list) {
model.addElement(brg);
}
cmbNama.setModel(model);
}
class ComboBoxListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Barang barang = (Barang) cmbNama.getSelectedItem();
if (barang != null) {
txtHarga.setText(String.valueOf(barang.getHarga()));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment