I'm writing a simple TODO list app in Java (IntelliJ IDEA). The app has a connection with a MySQL database. Everything seems to be fine, but my problem is that the user's text is not being displayed in my database. Instead of the text, it shows either an empty text field or the default text I entered.The same issue in the IntelliJ console(System.out.println).
I think the error might be in the AppFrame class, specifically in the addtask listener or in the addTaskToDatabase method, or I may have incorrectly set the return value in the getter method in the Task class.
My full code is here: https://github.com/lenkZel/TODOapp.git
My mysql database is here: USE todoapp; CREATE TABLE tasks( task_id INT PRIMARY KEY AUTO_INCREMENT, task_name VARCHAR(1000), is_done boolean );
//in AppFrame class:
public AppFrame() throws SQLException {
this.setTitle("TODOapp");
this.setSize(400, 700);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setVisible(true);
this.add(this.title, BorderLayout.NORTH);
this.add(this.btnpanel, BorderLayout.SOUTH);
this.add(this.list, BorderLayout.CENTER);
addtask = btnpanel.getaddtaskbtn();
clear = btnpanel.getclearbtn();
novyText = new JTextField();
addlistener();
database = new Database();
}
public void addlistener() {
addtask.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
Task task = new Task(novyText.getText());
list.add(task);
list.indexnum();
revalidate();
addTaskToDatabase(task);
}
public void addTaskToDatabase(Task task) {
String taskName = task.getTaskname();
boolean isDone = task.isDone();
String query = "INSERT INTO tasks (task_name, is_done) VALUES (?,?)";
try {
PreparedStatement statement = database.getConnection().prepareStatement(query);
statement.setString(1, taskName);
statement.setBoolean(2, isDone);
statement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("Query: " + query);
System.out.println("Task Name: " + taskName);
System.out.println("Is Done: " + isDone);
}
}
//in Task class:
taskname = new JTextField(initialText);
taskname.addFocusListener(this);
taskname.setPreferredSize(new Dimension(10, 20));
taskname.setBorder(BorderFactory.createEmptyBorder());
taskname.setBackground(new Color(255, 255, 255));
this.add(this.taskname);
@Override
public void focusGained(FocusEvent e) {
if (taskname.getText().equals("enter task")) {
taskname.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
}
public String getTaskname() {
return taskname.getText();
}
public boolean isDone() {
return taskname.getBackground() == Color.LIGHT_GRAY;
}