How can I remove a row from database using Mysql database using JTable. What I'm trying to do is when user select the row and click delete button I want to delete that row from data base.
private void deleteItemBtn1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
try{
if(jTable2.getSelectedRowCount()== 1){
int SelectedRowIndex = jTable2.getSelectedRow();
int row = jTable2.getSelectedRow();
String eve = model.getValueAt(row, 4).toString();
expenseDAO.deleteRow(eve);
model.removeRow(SelectedRowIndex);
}else{
if(jTable2.getRowCount()==0){
JOptionPane.showMessageDialog(this,"Table is Empty");
}else{
JOptionPane.showMessageDialog(this,"Please slelect s ingle row for Delete");
}
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null, ex);
}
}
This is my deleteRow method :
public void deleteRow(String value){
String query = "DELETE FROM expense WHERE ex_id ="+value;
Statement st;
try {
st = con.createStatement();
st.executeQuery(query);
} catch (SQLException ex) {
Logger.getLogger(ExpenseDAO.class.getName()).log(Level.SEVERE, null, ex);
}
}
This code not working.
Related
I would like to know how can I reference a java class in my jFrame form to display data on the jTable. This is a code from my jFrame and I want to know how can I put it in a java class and just reference the class here in the JFrame so I could save space in this JFrame form
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
Something like this?
public class CustomActionHandler {
private JComboBox jComboBox1;
// all the necessary stuff you need for the code to work
CustomActionHandler(JComboBox jComboBox1, etc...) {
this.jComboBox1 = jComboBox1;
// finish passing all the data here
}
public static void JComboActionFollowup() {
// TODO add your handling code here:
String sql = "select * from description";
if(jComboBox1.getSelectedIndex() == 0)
try{
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
jTable1.removeColumn(jTable1.getColumnModel().getColumn(2));
model.setRowCount(0);
while (rs.next()){
model.addRow(new String[]{rs.getString(1), rs.getString(2), rs.getString(3), rs.getString(4)});
}
} catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
}
and in your JFrame:
private CustomActionHandler actionhandler = new CustomActionHandler(jComboBox1, etc...)
private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {
actionhandler.JComboActionFollowup();
}
I have one table where it shows some data from sql server and when I click it it also shows data on text fields that gets it directly from the table. But once I click one row on the table it remains clicked until the frame is closed. How can I disable it? Heres my code on click event.
int rowIndex;
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
rowIndex = jTable1.getSelectedRow();
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
if(model.getValueAt(rowIndex, 3).toString().equals("Mashkull "))
{
jRadioButton1_mashkull1.setSelected(true);
jRadioButton2_femer1.setSelected(false);
} else {
jRadioButton2_femer1.setSelected(true);
jRadioButton1_mashkull1.setSelected(false);
}
jTextField1_id1.setText(model.getValueAt(rowIndex, 0).toString());
jTextField1_emri1.setText(model.getValueAt(rowIndex, 1).toString());
jTextField1_mbiemri2.setText(model.getValueAt(rowIndex, 2).toString());
jTextField1_nrtel1.setText(model.getValueAt(rowIndex, 5).toString());
jTextArea1_adresa1.setText(model.getValueAt(rowIndex, 6).toString());
Date bdate;
try {
bdate= new SimpleDateFormat("yyyy-MM-dd").parse(model.getValueAt(rowIndex, 4).toString());
jDateChooser1_data1.setDate(bdate);
} catch (ParseException ex) {
Logger.getLogger(kontrollostudentet.class.getName()).log(Level.SEVERE, null, ex);
}
}
You can make a call to clearSelection() right after getting the row index.
public void clearSelection()
Deselects all selected columns and rows.
I have an item database (jdbc) the functionality is: insert, delete, and update using GUI JTable, all work good but I need to display the image in the JTable but I couldn't :(
If you could help me in that, here's the code for the main functionality:
fill Table method:
try{
connection= DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
} catch(SQLException ex){
JOptionPane.showMessageDialog(null, ex);}
add method:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
update method:
try{
PreparedStatement update =connection.prepareStatement("update item set "
+ "name=? , price=?, image=? where id=?""
+"VALUES(?,?,?,?)");
update.setString(1, nameTextField.getText());
update.setDouble(2, Double.parseDouble(priceTextField.getText()));
update.setByte(3, image);
update.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = update.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
delete method:
try{
Statement delete = connection.createStatement();
delete.executeUpdate("delete from item where id="+IDTextField.getText());
priceTextField.setText("");
nameTextField.setText("");
idTextField.setText("");
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
A button event to choose image from JFileChooser:
String imagePath = null;
JFileChooser file;
private void ChooseImageButtonActionPerformed(java.awt.event.ActionEvent evt){
int result = file.showSaveDialog(null);
if(result == JFileChooser.APPROVE_OPTION){
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
imagePath = path;
}
}
The important methods are fillTable() and add().
fillTable method could be like this:
//you need a TableModel, let´s call it model and let´s call your JTable myJTable
TableModel model = (javax.swing.table.DefaultTableModel) myJTable.getModel();
myJTable.setModel(model);
//try to add results
try {
connection = DriverManager.getConnection(url, usr, pas);
statement = connection.createStatement();
resultSet = statement.executeQuery("select * from item");
while (resultSet.next()) {
//after your query, get the Image
Blob blob = resultSet.getBlob(3);//column 3
byte[] data = blob.getBytes(1, (int) blob.length());
BufferedImage img = null;
img = ImageIO.read(new ByteArrayInputStream(data));
Icon imgToTable = imageToIcon(img);//use the method below
//add row to your table (throught the model)
model.addRow(new Object[]{resultSet.getObject(1).toString(), resultSet.getObject(2).toString(), imgToTable,resultSet.getObject(4).toString()});
//itemTable.setModel(DbUtils.resultSetToTableModel(resultSet));
}
resultSet.close();
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
Add method could be like this:
try{
PreparedStatement insert =connection.prepareStatement("INSERT INTO items"
+"(name, price, image, ID)"
+"VALUES(?,?,?,?)");
insert.setString(1, nameTextField.getText());
insert.setDouble(2, Double.parseDouble(priceTextField.getText()));
//i recommend to use something like this to configure you image
file = new File(imagePath);
fis = new FileInputStream(file);
if (null == fis) {
fis = new FileInputStream(imagePath);
}
//configure image
insert.setBinaryStream(3, fis);
// insert.setByte(3, image);
insert.setInt(4, Integer.parseInt(IDTextField.getText()));
int row = insert.executeUpdate();
fillTable();
}catch (SQLException ex){
JOptionPane.showMessageDialog(null,ex);}
And use this to convert from Image to Icon (to put it in a Table Cell):
//from Image a Icon
public Icon imageToIcon(Image image) {
ImageIcon imgIcon = new ImageIcon(image);
Icon iconReturn = (Icon) imgIcon;
return iconReturn;
}
If in your database you are not using blob let me know.
I have a jTable. It has 6 column. I need to enter name in column 1 and once I press enter key the other 5 columns must be populated from database. Can anyone help please?
private void jTable2KeyPressed(java.awt.event.KeyEvent evt) {
{
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
{
// Object s=jTable2.getModel().getValueAt(1, 1);
//System.out.println("Value" +s);
Object Name= jTable2.getModel().getValueAt(1, 1);;
try {
openconn();
PreparedStatement ps;
System.out.println("Val" +Name);
ps = conn.prepareStatement("select * from inventory.addproducts where name='"+Name+"'");
rs= ps.executeQuery();
if(rs.next())
{
String rate=rs.getString(2);
jTable2.getModel().setValueAt(rate, 2, 3);
}
else
{
JOptionPane.showInputDialog("Wrong input");
}
conn.close();
}
catch(Exception ex)
{
}
}}
}
Hope this will make sense how to do it, use DefaultTableModel to populate your JTabel, a simple example, have not tried it out:
private DefaultTableModel model=new DefaultTableModel();
private JTable table=new JTable(model);
private JButton submit =new JButton("Submit");
public void populate(){
submit.addActionListener(e->{model.addRow(new Object[]{textField.getText(),database.getSurname(),database.getAge()});})
}
I am trying to make a ToDoList , and I create a jButton to remove a Task from the Database ,when i check the index it always gives (-1)
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);}
update:
// set DefaultListModel
tasksListModel = new DefaultListModel();
jListTasks.setModel(tasksListModel);
Then I create this method
// to clear and fill list every time method invoked
private void fillTaskList() {
tasksListModel.clear();
try {
resultSet = pstmt.executeQuery();
while (resultSet.next()) {
// System.out.println("xxx");
tasksListModel.addElement("\"" + resultSet.getString("task_name") +
"\"" + " starts at " + resultSet.getString("start_time"));
}
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
and this is the ActionListener of the RemoveButton
jbtnRemoveTask.addActionListener((ActionEvent e) -> {
// to fill the list with latest values in database
sqlQuery = "SELECT * FROM tasks";
try {
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
// to restore the Frame to default size as I change size during the using of application
if (ToDoFrame.this.getSize().width > 515 || ToDoFrame.this.getSize().height > 440) {
// implementation for these two methods comes at the end
decreaseHeight();
decreaseWidth();
}
// System.out.println(jListTasks.getLastVisibleIndex());
// System.out.println(jListTasks.getSelectedIndex());
// this code is always executed even there is item selected
if (jListTasks.getSelectedIndex() == -1) {
JOptionPane.showMessageDialog(null, "No task selected!!");
} else {
JOptionPane.showConfirmDialog(null, "Are you sure?!", "Remove task", JOptionPane.YES_NO_OPTION);
try {
// System.out.println(jListTasks.getSelectedValue());
String s = jListTasks.getSelectedValue().toString();
s = s.substring(s.length() - 5);
// System.out.println(s);
// the code for updating database
sqlUpdate = "DELETE FROM tasks WHERE start_time = ?";
pstmt = connection.prepareStatement(sqlUpdate);
pstmt.setString(1, s);
pstmt.executeUpdate();
JOptionPane.showMessageDialog(null, "Task removed successfully!");
sqlQuery = "SELECT * FROM tasks";
pstmt = connection.prepareStatement(sqlQuery);
fillTaskList();
} catch (SQLException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
// here are the code of decreaseWidth and decreaseHeight methods
private void decreaseWidth() {
for (int i = ToDoFrame.this.getSize().width; i > 510; i -= 10) {
ToDoFrame.this.setSize(i, ToDoFrame.this.getSize().height);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private void decreaseHeight() {
for (int i = ToDoFrame.this.getSize().height; i > 435; i -= 10) {
ToDoFrame.this.setSize(ToDoFrame.this.getSize().width, i);
ToDoFrame.this.setLocationRelativeTo(null);
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(ToDoFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Note: the code was working perfectly before making methods to re-size the Frame , when doing the re-sizing directly inside the ActionListener
Thanks for help
It looks like the action listener of your remove button calls the fillTaskList method before retrieving the selected index. The refill of the todo list will clear the selection in the list and the call to jListTasks.getSelectedIndex() will return -1.
I think you only need to update the todo list after removing the selected item.