Everytime I delete something from my JButton it deletes in the database but my jpanel wont update...
I wonder if there is an easy fix for this?
private void DeleteActionPerformed(java.awt.event.ActionEvent evt) {
infLabel.setText(inform[2]);
Connection connection = FlatFinder.getConnection();
Statement selectStmt = null;
try {
selectStmt = connection.createStatement();
Flat activeFlat = (Flat) AdminAll.getSelectedValue();
String sql = String.format(
"DELETE FROM `flats` WHERE flat_id = %d",
activeFlat.getId()
);
selectStmt.executeUpdate(sql);
} catch (SQLException ex) {
Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.repaint();
}
This is my current code. Is there any easy solution to update the jpanel when I press the delete button?
Related
I want to update my table right after clicking on a diffrent item in combobox. After adding actionPerformed combobox shows only the first item and the arrow doesn't work. I'm updating my table after selecting a diffrent item and clicking a button. Action perform in a button does work. Am I using the actionPerformed incorrectly?
Here is a code how I add items to a combobox.
private void fillComboBox() {
try {
DatabaseMetaData meta = (DatabaseMetaData) conn.getMetaData();
rs = meta.getTables("db", null, null, new String[] {
"TABLE"
});
while (rs.next()) {
ComboBox.addItem(rs.getString("TABLE_NAME"));
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null,e);
}
}
Here is how I fill the table.
private void fillTable()
{
String selectedValue = ComboBox.getSelectedItem().toString();
String sql = "Select * from "+selectedValue;
Statement stmt;
try {
stmt = conn.createStatement(rs.TYPE_SCROLL_INSENSITIVE,rs.CONCUR_UPDATABLE);
rs = stmt.executeQuery(sql);
Table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
Logger.getLogger(Welcome.class.getName()).log(Level.SEVERE, null, ex);
}
}
And after clicking a button, I update the table
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
fillTable();
}
Works fine, but I would like to update the table right after clicking on a new item in combobox.
Edit: I fixed it by adding fillComboBox() after fillTable(). But now I have two first items in combobox even after removeAll(). How do I fix it?
public Welcome() {
initComponents();
conn = MySqlConnect.ConnectDB();
fillComboBox();
fillTable();
ComboBox.removeAll();
fillComboBox();
repaint();
}
I always change contents of a ComboBox dynamically by using the underlying Model, not through the actual ComboBox. After your GUI is already shown, I think this matters ... using the model, not the JComboBox itself.
...
final var model = new DefaultComboBoxModel<String>();
while (rs.next()) {
model.addElement(rs.getString("TABLE_NAME"));
}
...
ComboBox.setModel(model);
I created a login GUI login form and tried to login if the username and password matches with that entered in the database. But, I am unable to login
I could not find any error in the code.
public class Login {
private JTextField nameTextField;
private JButton submitButton;
private JTextField passwordTextField;
private JLabel Message;
private JPanel LoginPanel;
public static void main(String[] args) {
JFrame frame=new JFrame("Login");
frame.setContentPane(new Login().LoginPanel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setSize(650,500);
frame.setVisible(true);
}
public Login() {
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Connection con = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/java_db", "root", "");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while (rs.next()) {
if (rs.getString("name").equals(nameTextField.getText()) && rs.getString("password").equals(passwordTextField.getText())) {
Message.setText("Login Success");
}
else {
Message.setText("Failed");
}
}
con.close();
} catch (SQLException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
}
});
}}
If the password and username matches, I want the application to show the message "Login Success"
Currently you're scanning the whole table and in fact check the username/password of the last element in the DB.
I would simply get the (unique) element corresponding to the username entered and verify the password.
Something like this:
PreparedStatement st = con.prepareStatement("SELECT password FROM employee WHERE name = ?");
st.setString(1, nameTextField.getText().trim());
ResultSet rs = st.executeQuery();
if (rs.next() && rs.getString(1).equals(passwordTextField.getText()))
Message.setText("Login Success");
else
Message.setText("Failed");
rs.close();
con.close();
I'm trying to display a list of data when I click on a button.
Now, I have a an homepage (a jframe that is the homepage of the program) with a button that will open the list frame and that button, when it will be clicked, will get the data from my DB and update the table.
This is the code that I've wrote on the button that is in the homepage and not in the list frame
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
try {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new List().setVisible(true);
}
});
this.dispose();
String DB_URL = "jdbc:mysql://localhost:3306/registropassword?autoReconnect=true&useSSL=false";
String DB_Username = "root";
String DB_Password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(DB_URL, DB_Username, DB_Password);
PreparedStatement prepstmt = null;
ResultSet rs = null;
String query = "SELECT * FROM registro";
prepstmt = conn.prepareStatement(query);
rs = prepstmt.executeQuery();
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
} catch (ClassNotFoundException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
}
}
NOTE:
On this line of code the jTable2, that is the name of the table that should be updated, I got a 'cannot find symbol' error on this line.
jTable2.setModel(DbUtils.resultSetToTableModel(rs));
Can someone help me to figure out where I'm wrong?
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.
I have write the code below. I can choose image using FileChooser clicking button a button(jButton5) on a Label(jLabel4). Now I want to save the imagePath in database clicking another button(jButton1). Which code should I write for jButton1.
Someone please help me.
private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser fc=new JFileChooser();
fc.showOpenDialog(this);
File f=fc.getSelectedFile();
String path=f.getAbsolutePath();
jLabel4.setIcon(new ImageIcon(path));
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
}
If you want to store file location into database
Upload the file to some location.
Get uploaded file path
store that file path into some table.
If you want to store Images directly into Databse
Create table like below (MySql)
CREATE TABLE `IMAGES` (
`ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`IMAGE` LONGBLOB NOT NULL,
PRIMARY KEY(`ID`)
)
TYPE = InnoDB;
In your actionlistener
PreparedStatement ps = null;
InputStream is = null;
try {
con = // get your database connection
ps = con.prepareCall("insert into IMAGES values (?)");
is = new FileInputStream(new File("file path"));
ps.setBinaryStream(1, is);
int count = ps.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally{
try{
if(is != null) is.close();
if(ps != null) ps.close();
if(con != null) con.close();
} catch(Exception ex){}
}