我正在使用javafx和sqllite构建此程序 我在fxml中有fx:id button1的按钮 和onAction:WriteToSql
package valgykla;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextField;
import javafx.event.ActionEvent;
/**
* FXML Controller class
*
* @author Lukas
*/
public class MeniuController implements Initializable {
@FXML
private Button button1;
@FXML
public static void WriteToSql(ActionEvent sql){
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("org.sqlite.JDBC");
con = DriverManager.
getConnection("jdbc:sqlite:database.db");
String query = "insert into Meniu(name,code) values(?,?)";
prSt = con.prepareStatement(query);
prSt.setString(1, "jack");
prSt.setString(12, "02545");
int count = prSt.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
// TODO Auto-generated catch block
}
// TODO Auto-generated catch block
finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
}
public void initialize(URL url, ResourceBundle rb) {
// TODO
}
}
遗憾的是我收到了错误
Caused by: javafx.fxml.LoadException: Error resolving onAction='#WriteToSql', either the event handler is not in the Namespace or there is an error in the script.
file:/C:/Users/Lukas/Desktop/lukasX/Valgykla/dist/run1382723305/Valgykla.jar!/valgykla/Meniu.fxml:29
答案 0 :(得分:1)
WriteToSql
方法为static
。 JavaFX不再考虑控制器的static
方法用于事件处理程序......(另见javafx 8 compatibility issues - FXML static fields)
只需删除static
关键字就可以解决问题。此外,由于您使用@FXML
对方法进行了注释,因此您还可以将其设为private
:
@FXML
private void WriteToSql(ActionEvent sql){
...
答案 1 :(得分:-1)