I want to save image file to my localhost MySQL database. Created Image (blob) column in personalDetails table.
As in screenshot, when I click on 'save' button every values correctly goes in database, but I can't do it for image .I've tried a lot of ways, but can't make it work. Here is all page code. There is also other connection code between data and MySQL. How can I make it ?
package sample.controllerPart;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;import javafx.fxml.Initializable;import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.StageStyle;import sample.helpers.plus;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.io.IOException;
import java.sql.*;
import java.util.ResourceBundle;
public class developersController implements Initializable {
FileInputStream fis;
#FXML private TextField nameField; #FXML private TextField familyNameField; #FXML private DatePicker dateOfBirthField; #FXML private TextField genderField; #FXML private TextField nationField; #FXML private TextField civilStatusField; #FXML private TextField profileCodeField;
#FXML private TextField workProgramming; #FXML private TextField workWebDesign; #FXML private TextField workOperatingSys; #FXML private TextField workDatabaseMng; #FXML private TextField workGraphicDesign; #FXML private TextField workPcHardware; #FXML private TextField workOther;
#FXML private TextField oPosition; #FXML private TextField oPhone; #FXML private TextField oMail; #FXML private TextField oGithub; #FXML private DatePicker oAdmissionDate; #FXML private TextField oLocation; #FXML private TextField oSalary;
#FXML private Text personalText; #FXML private Text personalText2; #FXML private Text personalText3; #FXML private Text personalText4; #FXML private Text personalText5; #FXML private Text personalText6; #FXML private Text personalText7;
#FXML private Text workText; #FXML private Text workText2; #FXML private Text workText3; #FXML private Text workText4; #FXML private Text workText5; #FXML private Text workText6; #FXML private Text workText7; #FXML private Text otherDetailText; #FXML private Text otherDetailText2; #FXML private Text otherDetailText3; #FXML private Text otherDetailText4; #FXML private Text otherDetailText5; #FXML private Text otherDetailText6; #FXML private Text otherDetailText7;
#FXML private Text listNFNText; #FXML private Text listNFNTextx; #FXML private Text listPText; #FXML private Text listPTextx; #FXML private Text listNFNText2; #FXML private Text listNFNTextx2; #FXML private Text listPText2; #FXML private Text listPTextx2; #FXML private Text listNFNText3; #FXML private Text listNFNTextx3; #FXML private Text listPText3; #FXML private Text listPTextx3; #FXML private Text listNFNText4; #FXML private Text listNFNTextx4; #FXML private Text listPText4; #FXML private Text listPTextx4; #FXML private Text listNFNText5; #FXML private Text listNFNTextx5; #FXML private Text listPText5; #FXML private Text listPTextx5; #FXML private Text listNFNText6; #FXML private Text listNFNTextx6; #FXML private Text listPText6; #FXML private Text listPTextx6;
#FXML
private ImageView imageData;
#FXML
private ImageView imageDatabase;
#FXML
private Button uPicture;
#FXML
private void uploadPhoto(ActionEvent event) {
FileChooser fc = new FileChooser();
fc.setTitle("Open File");
File selectedFile = fc.showOpenDialog(null);
String url = selectedFile.toURI().toString();
if(selectedFile != null) {
imageData.setImage(new Image(url));
imageData.maxWidth(119);
imageData.maxHeight(169);
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#FXML private void add_developers(javafx.scene.input.MouseEvent mouseEvent) throws IOException {
Dialog parentDialog = new Dialog();
Parent root = plus.loadFXML("add_developers");
parentDialog.getDialogPane().setContent(root);
root.setStyle("-fx-background-color:transparent");
parentDialog.initStyle(StageStyle.TRANSPARENT);
parentDialog.show(); }
int v = 0;
#FXML private void savePersonal (MouseEvent mouseEvent) throws SQLException {
ResultSet rs = null;
PreparedStatement pst = null;
DatePicker pw;
sample.controllerPart.ConnectionClass connectionClass = new sample.controllerPart.ConnectionClass();
Connection connection = connectionClass.getConnection();
String sql = "INSERT INTO PERSONALDETAILS" +
"(Name, familyName, dateOfBirth,gender, nation, civilStatus, profileCode, programmingExp, webDesignExp, operatingSysExp, databaseMngExp, graphicDesignExp, pcHardwareExp, otherExp, position, phone, mail, github, admissionDate, location, salary) " +
"VALUES('"+nameField.getText()+"', '"+familyNameField.getText()+"', '"+dateOfBirthField.getValue()+"'," + " '"+genderField.getText()+"', '"+nationField.getText()+"', '"+civilStatusField.getText()+"', '"+profileCodeField.getText()+"', '" +workProgramming.getText()+"','"+workWebDesign.getText()+"','"+workOperatingSys.getText()+"','"+workDatabaseMng.getText()+"', '"+workGraphicDesign.getText()+"', '"+workPcHardware.getText()+"','"+workOther.getText()+"', '" +oPosition.getText()+"','"+oPhone.getText()+"','"+oMail.getText()+"','"+oGithub.getText()+"','"+oAdmissionDate.getValue()+"','"+oLocation.getText()+"','"+oSalary.getText()+"')";
Statement statement = connection.createStatement();
statement.executeUpdate(sql);
String query = "SELECT * FROM PERSONALDETAILS where name = ?";
pst = connection.prepareStatement(query);
pst.setString(1, (String) nameField.getText());
rs = pst.executeQuery();
int x = 0;
while(rs.next()){
personalText.setText(rs.getString("name"));
personalText2.setText(rs.getString("familyName"));
personalText3.setText(rs.getString("dateOfBirth"));
personalText4.setText(rs.getString("gender"));
personalText5.setText(rs.getString("nation"));
personalText6.setText(rs.getString("civilStatus"));
personalText7.setText(rs.getString("profileCode"));
workText.setText(rs.getString("programmingExp"));
workText2.setText(rs.getString("webDesignExp"));
workText3.setText(rs.getString("operatingSysExp"));
workText4.setText(rs.getString("databaseMngExp"));
workText5.setText(rs.getString("graphicDesignExp"));
workText6.setText(rs.getString("pcHardwareExp"));
workText7.setText(rs.getString("otherExp"));
otherDetailText.setText(rs.getString("position"));
otherDetailText2.setText(rs.getString("phone"));
otherDetailText3.setText(rs.getString("mail"));
otherDetailText4.setText(rs.getString("github"));
otherDetailText5.setText(rs.getString("admissionDate"));
otherDetailText6.setText(rs.getString("location"));
otherDetailText7.setText(rs.getString("salary"));
}
pst.close();
rs.close();
if (v == 0) {
listNFNText.setText(personalText.getText());
listNFNTextx.setText(personalText2.getText());
listPText.setText(otherDetailText.getText());
listPTextx.setText(personalText7.getText());
v = 1;
}
else if (v == 1) {
listNFNText2.setText(personalText.getText());
listNFNTextx2.setText(personalText2.getText());
listPText2.setText(otherDetailText.getText());
listPTextx2.setText(personalText7.getText());
v = 2;
}
else if (v == 2) {
listNFNText3.setText(personalText.getText());
listNFNTextx3.setText(personalText2.getText());
listPText3.setText(otherDetailText.getText());
listPTextx3.setText(personalText7.getText());
v = 3;
}
else if (v == 3) {
listNFNText4.setText(personalText.getText());
listNFNTextx4.setText(personalText2.getText());
listPText4.setText(otherDetailText.getText());
listPTextx4.setText(personalText7.getText());
v = 4;
}
else if (v == 4) {
listNFNText5.setText(personalText.getText());
listNFNTextx5.setText(personalText2.getText());
listPText5.setText(otherDetailText.getText());
listPTextx5.setText(personalText7.getText());
v = 5;
}
else if (v == 5) {
listNFNText6.setText(personalText.getText());
listNFNTextx6.setText(personalText2.getText());
listPText6.setText(otherDetailText.getText());
listPTextx6.setText(personalText7.getText());
v = 0;
}
}}
Use SwingFXUtils to convert to BufferedImage and use ImageIO to save the data to a ByteArrayOutputStream. A Blob created from the resulting byte[] array used with PreparedStatement to insert the data to the db.
private Connection conn;
#Override
public void init() throws Exception {
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser(USERNAME);
dataSource.setPassword(PASSWORD);
dataSource.setServerName(SERVER);
dataSource.setDatabaseName(DATABASE_NAME);
conn = dataSource.getConnection();
try (Statement stm = conn.createStatement()) {
// initialize table
stm.execute("CREATE TABLE IF NOT EXISTS images ("
+ "id INT AUTO_INCREMENT PRIMARY KEY, "
+ "image LONGBLOB)");
}
}
#Override
public void stop() throws Exception {
if (conn != null) {
conn.close();
}
}
#Override
public void start(Stage primaryStage) {
ImageView imageView = new ImageView();
Button open = new Button("open");
Button submit = new Button("submit");
Button retrieve = new Button("retrieve");
TextField tf = new TextField();
TextFormatter<Integer> formatter = new TextFormatter<>(new IntegerStringConverter());
tf.setTextFormatter(formatter);
open.setOnAction(evt -> {
FileChooser chooser = new FileChooser();
File file = chooser.showOpenDialog(primaryStage);
if (file != null) {
Image image = new Image(file.toURI().toString());
imageView.setImage(image);
}
});
submit.setOnAction(evt -> {
Image image = imageView.getImage();
Integer id = formatter.getValue();
if (image != null && id != null) {
try (PreparedStatement stm = conn.prepareStatement("INSERT INTO images (id, image) VALUES (?, ?) ON DUPLICATE KEY UPDATE image = ?")) {
// write data to in-memory stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BufferedImage bi = SwingFXUtils.fromFXImage(image, null);
ImageIO.write(bi, "jpg", bos);
Blob blob = new SerialBlob(bos.toByteArray());
stm.setInt(1, id);
stm.setBlob(2, blob);
stm.setBlob(3, blob);
stm.executeUpdate();
} catch (IOException | SQLException ex) {
ex.printStackTrace();
}
}
});
retrieve.setOnAction(evt -> {
Integer id = formatter.getValue();
if (id != null) {
imageView.setImage(null);
try (PreparedStatement stm = conn.prepareStatement("SELECT image FROM images WHERE id = ?")) {
stm.setInt(1, id);
ResultSet rs = stm.executeQuery();
if (rs.next()) {
// read image data from db
Blob data = rs.getBlob(1);
imageView.setImage(new Image(data.getBinaryStream()));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
VBox root = new VBox(tf, new HBox(open, submit, retrieve), imageView);
Scene scene = new Scene(root, 500, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
Related
I have two Controller class(Controller and Dailog Controller). COntroller class has tableView. On Double click on Tableview row the Dialog popup. The dialogController class has two button i.e update and delete.
The Update button updating and deleting data in database. After updating or deleting i want to refresh tableview. The problem is tablview refresh method is in Controller class. So how can i refresh it?
public class Controller implements Initializable{
#FXML
private TabPane tabPane;
#FXML
private Tab createTaskTab;
#FXML
private TextArea textArea;
#FXML
private Button saveBtn;
#FXML
private Tab viewTasksTab;
#FXML
private TableView<Task> tableView;
#FXML
private TableColumn<Task, Integer> idColumn;
#FXML
private TableColumn<Task, String> dateColumn;
#FXML
private TableColumn<Task, String> timeColumn;
#FXML
private TableColumn<Task, String> taskColumn;
#FXML
private TableColumn<Task, String> statusColumn;
#FXML
void saveTask(ActionEvent event) {
String getTask = textArea.getText();
if(getTask.length() > 0)
{
MysqlConnection mysqlConnection = new MysqlConnection();
int count = mysqlConnection.insertTask(getTask);
if(count > 0)
{
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle("Saved");
alert.setContentText("Task Saved");
alert.show();
textArea.clear();
}
}
else
{
Alert alert = new Alert(AlertType.WARNING);
alert.setTitle("Empty TextArea");
alert.setContentText("Please write the task");
alert.show();
}
}
#FXML
public void viewTasks(Event e)
{
try{
tabPane.getSelectionModel().selectedItemProperty().addListener(
new ChangeListener<Tab>() {
#Override
public void changed(ObservableValue<? extends Tab> observable, Tab oldValue, Tab newValue) {
if(newValue == viewTasksTab)
{
refreshTable();
}
}
});
}catch(Exception exception)
{
System.out.println("Exception in viewTasks");
}
}
protected void refreshTable() {
MysqlConnection myconn = new MysqlConnection();
idColumn.setCellValueFactory(new PropertyValueFactory<>("id"));
dateColumn.setCellValueFactory(new PropertyValueFactory<>("date"));
timeColumn.setCellValueFactory(new PropertyValueFactory<>("time"));
taskColumn.setCellValueFactory(new PropertyValueFactory<>("task"));
statusColumn.setCellValueFactory(new PropertyValueFactory<>("status"));
tableView.setItems(myconn.fetchTasks());
}
#FXML
public void onEdit(MouseEvent event)
{
if(event.getClickCount() == 2){
Task selectedTask = tableView.getSelectionModel().getSelectedItem();
Scene scene;
Stage stage;
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("DialogBox.fxml"));
Parent root = (Parent) loader.load();
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
scene = new Scene(root);
stage = new Stage();
stage.initModality(Modality.APPLICATION_MODAL);
stage.setScene(scene);
stage.showAndWait();
} catch (IOException e) {
System.out.println("Exception in onEdit"+e.getMessage());
}
}
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
}
DialogController class:
[public class DialogBoxController implements Initializable{
#FXML
private Label idLabel;
#FXML
private Label dateLabel;
#FXML
private Label timeLabel;
#FXML
private ComboBox<String> statusComboBox;
#FXML
private TextArea textAreaDialog;
#FXML
private Button updateBtn;
#FXML
private Button deleteBtn;
private void closeStage(ActionEvent event) {
Node source = (Node) event.getSource();
Stage stage = (Stage) source.getScene().getWindow();
stage.close();
}
public void editTask(Task task)
{
idLabel.setText(""+task.getId());
dateLabel.setText(task.getDate());
timeLabel.setText(task.getTime());
textAreaDialog.setText(task.getTask());
statusComboBox.setValue(task.getStatus());
textAreaDialog.setEditable(false);
}
#FXML
public void update(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
String status = statusComboBox.getSelectionModel().getSelectedItem().toString();
MysqlConnection myconn = new MysqlConnection();
myconn.updateTask(taskID, status);
closeStage(event);
}
#FXML
public void delete(ActionEvent event){
int taskID = Integer.parseInt(idLabel.getText());
MysqlConnection myconn = new MysqlConnection();
myconn.deleteTask(taskID);
closeStage(event);
}
#Override
public void initialize(URL location, ResourceBundle resources) {
statusComboBox.getItems().addAll("Pending","Done","Aborted");
}
Snapcshot of Application
You can add this to the DialogBoxController class:
public class DialogBoxController {
private Controller controller;
public void setController(Controller controller){
this.controller = controller;
}
#FXML
public void delete(ActionEvent event){
// Your code
controller.refreshTable();
closeStage(event);
}}
And in the Controller:
DialogBoxController dialog = loader.getController();
dialog.editTask(selectedTask);
dialog.setController(this);
The tableview only shows newly added data when I restart the program.
The steps I follow to add the new item are:
dialogCadastro
Confirm the registry
update the table
However, updating the table does not work.
This is my code:
public class ControllerTelaOperacoes implements Initializable {
#FXML
TableView<Item> tblItem;
#FXML
TableColumn<Item, String> colCodigoItem;
#FXML
TableColumn<Item, String> colDescricaoItem;
#FXML
TableColumn<Item, String> colValorItem;
#FXML
TableColumn<Item, String> colQuantidadeItem;
#FXML
TableColumn<Item, String> colFornecedorItem;
#FXML
TextField txtQuantidadeItem;
#FXML
TextField txtValorItem;
#FXML
TextField txtDescricaoItem;
// #FXML
// ComboBox cbxFornecedorItem;
#FXML
Button btnConfirmarEstoqueAtualizar;
#FXML
Button btnConfirmarEstoqueCadastro;
#FXML
TextField txtIDAtualizar;
#FXML
Button btnCadastrarItem;
#FXML
Button btnAtualizarItem;
#FXML
Button btnEfetuarVenda;
private static Scene dialogEstoqueCadastrar;
private static Scene dialogEstoqueAtualizar;
private static Scene dialogEfetuarVenda;
private String dados;
public String getDados() {
return dados;
}
public void setDados(String dados) {
this.dados = dados;
}
#FXML
public void CadastrarItem() throws IOException {
tblItem.refresh();
Parent fxmldialogEstoqueCadastro = FXMLLoader
.load(getClass().getResource("/views/dialogEstoqueCadastrar.fxml"));
dialogEstoqueCadastrar = new Scene(fxmldialogEstoqueCadastro);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Cadastrar item");
primaryStage.setScene(dialogEstoqueCadastrar);
primaryStage.show();
}
#FXML
public void AtualizarItem() throws IOException {
tblItem.refresh();
Parent fxmldialogEstoqueAtualizar = FXMLLoader
.load(getClass().getResource("/views/dialogEstoqueAtualizar.fxml"));
dialogEstoqueAtualizar = new Scene(fxmldialogEstoqueAtualizar);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Atualizar item");
primaryStage.setScene(dialogEstoqueAtualizar);
primaryStage.show();
}
#FXML
public void EfetuarVenda() throws IOException {
tblItem.refresh();
Parent fxmldialogEfetuarVenda = FXMLLoader.load(getClass().getResource("/views/dialogEfetuarVenda.fxml"));
dialogEfetuarVenda = new Scene(fxmldialogEfetuarVenda);
Stage primaryStage = new Stage();
Image image = new Image("/img/iconeSistema.png");
primaryStage.setResizable(false);
primaryStage.getIcons().add(image);
primaryStage.setTitle("Efetuar Venda");
primaryStage.setScene(dialogEfetuarVenda);
primaryStage.show();
}
// CONTROLE DE ESTOQUE
#Override
public void initialize(URL url, ResourceBundle rb) {
// conecta tabela com o bd
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con;
con = DriverManager.getConnection("jdbc:mysql://127.0.0.1/bdprojetointegrador", "root", "");
System.out.println("TESTE TABELA 1");
Statement stmt = con.createStatement();
System.out.println("TESTE TABELA 2");
ResultSet rs = stmt.executeQuery("SELECT * FROM item");
System.out.println("TESTE TABELA 3");
while (rs.next()) {
ObservableList<Item> dados = FXCollections
.observableArrayList(new Item(rs.getString("codigo"), rs.getString("descricao"),
rs.getString("valor"), rs.getString("quantidade"), rs.getString("fornecedor_codigo")));
System.out.println("TESTE TABELA 4");
tblItem.getItems().addAll(dados);
colCodigoItem.setCellValueFactory(new PropertyValueFactory<>("codigo"));
colDescricaoItem.setCellValueFactory(new PropertyValueFactory<>("descricao"));
colValorItem.setCellValueFactory(new PropertyValueFactory<>("valor"));
colQuantidadeItem.setCellValueFactory(new PropertyValueFactory<>("quantidade"));
colFornecedorItem.setCellValueFactory(new PropertyValueFactory<>("fornecedor_codigo"));
System.out.println("TESTE TABELA 5");
}
stmt.close();
rs.close();
con.close();
System.out.println("TESTE 6");
} catch (
ClassNotFoundException e1) {
Alert classe = new Alert(AlertType.ERROR);
classe.setContentText("Classe não encontrada!");
classe.show();
} catch (SQLException e2) {
// ESTÁ CHAMANDO ESTA FUNÇÃO
Alert classe = new Alert(AlertType.ERROR);
classe.setContentText("Matricula já existente! ERRO: " + e2);
classe.show();
}
}
}
i am new here, am new in programming and i am trying to create a Java app with Selenium and JavaFX. In this app i should be able to check the links of a page and also could be able to show the pointed link. For the moment the programm can check all the links on a page but it can't show the correct link. I display all urls in a ListView with a button and in this buttons calls the method to show the link but for every button in the list it always shows the same url/link because it is the last value taken from the variable url in a while loop. And also i have 4 tabs where i track the HTTP Status of each link. For all 200 HTTP status they are inserted in the "200s" tab, for the 300 in the "300s" tab, the same for the 400 and 500. I have a variable respCode for the HTTP status but it always displays the last value in the while loop (200). Here is a code snippet to have a look on it:
public class AutoTestController
{
// location and resources will be automatically injected by the FXML loader
#FXML
private Button buttonSearch;
#FXML
private Button buttonCheck;
#FXML
private Button buttonAllLinks;
#FXML
private ChoiceBox switchLogin;
#FXML
private TextField testUrl;
#FXML
private TextField stageUrl;
#FXML
private TextField stageIntUrl;
#FXML
private TextField testUrlLiveInt;
#FXML
private TextField testUrlStage;
#FXML
private TextField testUrlStageInt;
#FXML
private TextField customerIdLogin;
#FXML
private TextField customerIdLoginLiveInt;
#FXML
private TextField oneCustomerIdLoginLiveInt;
#FXML
private TextField customerIdLoginStage;
#FXML
private TextField customerIdLoginStageInt;
#FXML
private TextField oneCustomerIdLoginStageInt;
#FXML
private PasswordField passwordLogin;
#FXML
private PasswordField passwordLoginStage;
#FXML
private PasswordField onePasswordLoginLiveInt;
#FXML
private PasswordField onePasswordLoginStageInt;
#FXML
private TextField linkText;
#FXML
private TextField linkTextTwo;
#FXML
private TextField linkTextThree;
#FXML
private TextField linkTextFour;
#FXML
private TextField linkTextFive;
#FXML
private TextField linkTextEmpty;
#FXML
private TextField linkTextAnother;
#FXML
private int textLinks;
#FXML
private ChoiceBox countrySelector;
#FXML
private ChoiceBox countrySelectorLiveInt;
#FXML
private StackPane paneTwo;
#FXML
private StackPane paneThree;
#FXML
private StackPane paneFour;
#FXML
private StackPane paneFive;
private static WebDriver driver = null;
#FXML
private int respCode = 200;
#FXML
private static int linkCount=0;
#FXML
private static int linkCountTwo=0;
#FXML
private static int linkCountThree=0;
#FXML
private static int linkCountFour=0;
#FXML
private static int linkCountFive=0;
#FXML
private static int linkCountEmpty=0;
#FXML
private static int linkCountAnother=0;
#FXML
private String url = "";
private int counter=0;
private ObservableList<String> listTwo;
private ObservableList<String> listThree;
private ObservableList<String> listFour;
private ObservableList<String> listFive;
private List<String> urlsTwo = new ArrayList<>();
private List list = new ArrayList<>();
private List<String[]> urlsTwo2 = new ArrayList<>();
private List<String> urlsThree = new ArrayList<>();
private List<String> urlsFour = new ArrayList<>();
private List<String> urlsFive = new ArrayList<>();
// Add a public no-args constructor
public AutoTestController()
{
}
public class XCell extends ListCell<String> {
HBox hB = new HBox();
Label label = new Label("Empty");
Pane pane = new Pane();
Button bB = new Button("Show Link");
String lastItem = "";
public XCell() {
super();
hB.getChildren().addAll(bB, new Text(" (" + respCode + ") : "), label, pane, new Text(" "));
HBox.setHgrow(paneTwo, Priority.ALWAYS);
bB.setUserData(url);
bB.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent eventTwo) {
Button thisButton = (Button) eventTwo.getSource();
WebElement linkTwo = driver.findElement(By.xpath("//a[contains(#href, '" + thisButton.getUserData() + "')]"));
scrolltoElement(linkTwo);
HighlightThisLink(driver, linkTwo);
}
});
}
#Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setText(null); // No text in label of super class
if (empty) {
lastItem = null;
setGraphic(null);
} else {
lastItem = item;
label.setText(item!=null ? item : "<null>");
setGraphic(hB);
}
}
}
#FXML
private void initialize()
{
countrySelector.getItems().addAll("DE","US","CA","UK","FR","ES","IT","MX");
countrySelector.getSelectionModel().selectFirst();
countrySelectorLiveInt.getItems().addAll("DE","US","CA","UK","FR","ES","IT","MX");
countrySelectorLiveInt.getSelectionModel().selectFirst();
}
#FXML
private void CheckLink(){
String theUrl = "";
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
HttpURLConnection huc = null;
driver.navigate();
List<WebElement> links = driver.findElements(By.tagName("a"));
linkCount = links.size();
System.out.println("Total Links on Page : "+linkCount);
linkText.setText("Total Links on Page : " + linkCount);
Iterator<WebElement> it = links.iterator();
while(it.hasNext()){
url = it.next().getAttribute("href");
if(url == null || url.isEmpty()){
System.out.println("URL is either not configured for anchor tag or it is empty");
linkCountEmpty++;
System.out.println("Number of empty urls : " + linkCountEmpty);
linkTextEmpty.setText("Number of empty urls : " + linkCountEmpty);
continue;
}
if(!url.startsWith(theUrl)){
System.out.println("URL " + url + " belongs to another domain, skipping it.");
linkCountAnother++;
System.out.println("Number of another domain : " + linkCountAnother);
linkTextAnother.setText("Number of other : " + linkCountAnother);
continue;
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode >= 200 && respCode <= 226) {
urlsTwo.add(url);
listTwo = FXCollections.observableArrayList(urlsTwo);
ListView<String> lvTwo = new ListView<>(listTwo);
lvTwo.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
paneTwo.getChildren().add(lvTwo);
System.out.println(respCode+": "+url+" is a success link");
linkCountTwo++;
System.out.println("Number of 200s : " + linkCountTwo);
linkTextTwo.setText("Number of 200s : " + linkCountTwo);
}
if(respCode >= 300 && respCode <= 308) {
urlsThree.add(url);
listThree = FXCollections.observableArrayList(urlsThree);
ListView<String> lvThree = new ListView<>(listThree);
lvThree.setUserData(respCode);
lvThree.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
paneThree.getChildren().add(lvThree);
System.out.println(respCode+": "+url+" is a redirection link");
linkCountThree++;
System.out.println("Number of 300s : " + linkCountThree);
linkTextThree.setText("Number of 300s : " + linkCountThree);
}
if(respCode >= 400 && respCode <= 499) {
urlsFour.add(url);
listFour = FXCollections.observableArrayList(urlsFour);
ListView<String> lvFour = new ListView<>(listFour);
lvFour.setUserData(respCode);
lvFour.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
paneFour.getChildren().add(lvFour);
System.out.println(respCode+": "+url+" is a client error link");
linkCountFour++;
System.out.println("Number of 400s : " + linkCountFour);
linkTextFour.setText("Number of 400s : " + linkCountFour);
}
if(respCode >= 500 && respCode <= 599) {
urlsFive.add(url);
listFive = FXCollections.observableArrayList(urlsFive);
ListView<String> lvFive = new ListView<>(listFive);
lvFive.setUserData(respCode);
lvFive.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> param) {
return new XCell();
}
});
paneFive.getChildren().add(lvFive);
System.out.println(respCode+": "+url+" is a server error link");
linkCountFive++;
System.out.println("Number of 200s : " + linkCountFive);
linkTextFive.setText("Number of 200s : " + linkCountFive);
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void scrolltoElement(WebElement ScrolltoThisElement) {
Coordinates coordinate = ((Locatable) ScrolltoThisElement).getCoordinates();
coordinate.onPage();
coordinate.inViewPort();
}
#FXML
private void HighlightThisLink(WebDriver driver, WebElement element) {
driver.navigate();
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].setAttribute('style', 'background: yellow; border: 2px solid red;');", element);
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
System.out.println(e.getMessage());
}
js.executeScript("arguments[0].setAttribute('style','border: solid 2px white')", element);
}
}
Here is a capture of the programm with JavaFX:
Link Checker Programm 200s
Link Checker Programm 300s
Could someone please help with these issues?
You don't seem to understand the way ListView works:
A ListView creates the cells that are required to display the items when they are needed. You don't control yourself when this is done. You should be able to deal with cell creation happening at any time. There is no 1:1 relation between cells and items. Items may be reassigned to different cells and there may not be a cell for every item.
For this reason retrieving info in cellFactory (which is what you do in your cell constructor) will not work.
You should change the item type allowing you to access all neccessary info and use the ListCell.item property in the Button handler of the cell:
private static class Response {
private final int responseCode;
private final String url;
Response(int responseCode, String url) {
this.responseCode = responseCode;
this.url = url;
}
// getters...
}
private static class XCell extends ListCell<Response> {
private final HBox hB = new HBox();
private final Label label = new Label("Empty");
private final Button bB = new Button("Show Link");
private final Text response = new Text();
public XCell() {
hB.getChildren().addAll(bB, response, label);
bB.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent eventTwo) {
// handle button click using info from cell item
Response item = getItem();
WebElement linkTwo = driver.findElement(By.xpath("//a[contains(#href, '" + item.getUrl() + "')]"));
scrolltoElement(linkTwo);
HighlightThisLink(driver, linkTwo);
}
});
}
#Override
protected void updateItem(Response item, boolean empty) {
super.updateItem(item, empty);
// update display
if (empty || item == null) {
setGraphic(null);
} else {
label.setText(item.getUrl());
response.setText("("+Integer.toString(item.getResponseCode()) + "):");
setGraphic(hB);
}
}
}
#FXML
private void initialize() {
listTwo = FXCollections.observableArrayList();
ListView<Response> lvTwo = new ListView<>(listTwo);
lvTwo.setCellFactory(lv -> new XCell());
paneTwo.getChildren().add(lvTwo);
listThree = FXCollections.observableArrayList();
ListView<Response> lvThree = new ListView<>(listThree);
lvThree.setCellFactory(l -> new XCell());
paneThree.getChildren().add(lvThree);
listFour = FXCollections.observableArrayList();
ListView<Response> lvFour = new ListView<>(listFour);
lvFour.setCellFactory(l -> new XCell());
paneFour.getChildren().add(lvFour);
listFive = FXCollections.observableArrayList();
ListView<Response> lvFive = new ListView<>(listFive);
lvFive.setCellFactory(l -> new XCell());
paneFive.getChildren().add(lvFive);
...
}
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
switch (respCode / 100) {
case 2:
if (respCode <= 226) {
listTwo.add(new Response(respCode, url));
System.out.println(respCode+": "+url+" is a success link");
linkCountTwo++;
System.out.println("Number of 200s : " + linkCountTwo);
linkTextTwo.setText("Number of 200s : " + linkCountTwo);
}
break;
case 3:
if (respCode <= 308) {
listThree.add(new Response(respCode, url));
...
}
break;
case 4:
listFour.add(new Response(respCode, url));
...
break;
case 5:
listFive.add(new Response(respCode, url));
...
break;
}
Trying to make a dictionary using JavaFx.
Here is my Controller class-
public class MainUIController implements Initializable {
DatabaseManager db=new DatabaseManager();
ObservableList<OvidhanMeaning> MeaningList;
#FXML
private TextField searchField;
#FXML
private ImageView searchIcon;
#FXML
private ImageView aboutIcon;
#FXML
private TableView<OvidhanMeaning> ovidhanTable;
#FXML
private TableColumn<OvidhanMeaning, String> englishCol;
#FXML
private TableColumn<OvidhanMeaning, String> banglaCol;
#Override
public void initialize(URL location, ResourceBundle resources) {
Image search = new Image(getClass().getResource("/images/search.png").toString(), true);
Image about = new Image(getClass().getResource("/images/about.png").toString(), true);
//Font bnFont = Font.loadFont(getClass().getResource("/fonts/Siyamrupali.ttf").toExternalForm(), 12);
Font bnFont = Font.loadFont(getClass().getResourceAsStream("/fonts/Siyamrupali.ttf"), 12);
searchIcon.setImage(search);
aboutIcon.setImage(about);
db.Connect("jdbc:sqlite::resource:ankurdb/bn_words.db");
ResultSet rs = db.GetResult("select en_word,bn_word from words");
MeaningList=FXCollections.observableArrayList();
try {
while(rs.next())
{
String enword = rs.getString("en_word");
String bnword = rs.getString("bn_word");
MeaningList.add(new OvidhanMeaning(enword,bnword));
englishCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("enword"));
banglaCol.setCellValueFactory(new PropertyValueFactory<OvidhanMeaning, String>("bnword"));
ovidhanTable.setItems(MeaningList);
}
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(MeaningList.size());
}
}
And here is my model class in which I loaded the data-
public class OvidhanMeaning {
private SimpleStringProperty enword;
private SimpleStringProperty bnword;
public OvidhanMeaning(String enword, String bnword) {
this.enword = new SimpleStringProperty(enword);
this.bnword = new SimpleStringProperty(bnword);
}
public String getenword() {
return enword.get();
}
public SimpleStringProperty enwordProperty() {
return enword;
}
public String getbnword() {
return bnword.get();
}
public SimpleStringProperty bnwordProperty() {
return bnword;
}
}
Now I'm trying to bind the searchField with the loaded MeaningList and populate the binded data into ovidhanTable.
How can I do this?
There is a class FXMLDocumentController.
There is a class ThreadForFile which has been inheriting from class Thread (which I read data from a file)
After I pressed the button (in the class FXMLDocumentController) I create a flow of class ThreadForFile.
I need to in the class ThreadForFile, when reading, the string displayed in the TextArea. But I can not figure out if I pass a parameter TextArea, and change it in the constructor, then there is a change in this component.But if I assign the class field this TextArea, it displays an error :
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException
ThreadForFile extends Thread
private String path;
private long ms;
private int id;
private String name;
private boolean stop = false;
private HTMLEditor web;
private DB db = new DB();
private Button doc;
public void setMS(long ms){
System.out.print(ms);
this.ms =ms;
}
public ThreadForFile(String name,String path,long ms,int id,Button doc) {
this.path = new String();
this.path = path;
this.ms = ms;
this.id = id;
this.name = name;
this.doc = new Button();
this.doc = doc;
}
public void Stop(boolean stop){
this.stop = stop;
}
public void run( ) {
try {
doc.setText("Zsczsc");
System.out.print("asdasd");
File file = new File(path);
File file1 = new File("C:\\out.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(new FileInputStream(file), "UTF-8"));
String line = null;
while( (line = br.readLine()) != null){
if(!Thread.interrupted()) //Проверка прерывания
{
if(!stop){
PrintWriter out = new PrintWriter(file1.getAbsoluteFile());
try {
sytem.out.print(line+"\n");
} finally {
out.close();
}
Thread.sleep(db.getParam().getMS()*1000);
System.out.print("ms" + db.getParam().getMS());
}
}else{
return;
}
}
} catch (Exception ex) {
System.out.print(ex.toString());
Logger.getLogger(ThreadForFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void read()throws FileNotFoundException, IOException
{
}
FXMLDocumentController
<!-- language: JavaFX -->
public class FXMLDocumentController implements Initializable {
private long ms = 5;
private ObservableList<ThreadForFile> threadForFile = FXCollections.observableArrayList();
private ObservableList<threadFile> threadFile = FXCollections.observableArrayList();
private int index ;
private DB db = new DB();
private Parametrs param = new Parametrs();
#FXML
private Button btnAdd;
#FXML
private Button btnStop;
#FXML
public Button btnDel;
#FXML
private Button btnStart;
#FXML
private TextField textFValueText;
#FXML
private TextField textFMs;
#FXML
private Button btnUpdate;
#FXML
public static TextArea textArea;
#FXML
private Label nameLabel;
#FXML
private Label pathLabel;
#FXML
private TextField textFName;
#FXML
private TextField textFPath;
#FXML
private TableColumn nameCol;
#FXML
private TableColumn pathCol;
#FXML
private TableColumn statCol;
public static FXMLDocumentController doc;
private ResourceBundle bundle;
#FXML
private TableView table;
#FXML
private void handleButtonAction(ActionEvent event) {
System.out.println("You clicked me!");
}
#Override
public void initialize(URL url, ResourceBundle rb) {
bundle = rb;
System.out.println("You clicked me!");
FileRead file = new FileRead(FXMLDocumentController.this);
Tab1();
Tab2();
Tab3();
param = db.getParam();
System.out.print(param.getMS() + " " + param.getValue());
}
public void Tab1()
{
}
public void Tab2()
{
//root.getChildren().addAll(btn,table,btnStop,btnStart,btnDel,nameField,pathField,name,path);
btnAdd.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
threadFile.add(new threadFile(textFName.getText(),textFPath.getText(),1));
threadForFile.add(new ThreadForFile(threadFile.get(threadFile.size()-1).getName(),threadFile.get(threadFile.size()-1).getPath(),ms,threadFile.size(),btnAdd));
threadForFile.get(threadForFile.size()-1).start();
index = table.getSelectionModel().getSelectedIndex();
System.out.print(index+ "\n");
}
});
.
.
.
.
.
.
.
.
.
.
}
You are trying to access a JavaFX Control outside the JavaFX Application thread.
Never use your controls, out of your Controller or pass them as a parameter to other methods. Instead, try to pass data to the controller, which in turn will set it to the controls inside the controller.
Some useful links are on passing data to the Controller :
Passing Parameters JavaFX FXML
How to have constructor with arguments for controller?
Some useful links on multi-threading in JavaFX:
How do I safely modify JavaFX GUI nodes from my own Thread?
JavaFX working with threads and GUI