So I'm making a login system. Based on the role your account has when you log in, it displays role specific buttons. For instance if you login as an employee, you get to see two buttons called RequestStatus and RegisterMissing. If you login as a manager, you get to see the buttons RequestStatus, RegisterMissing, Reports and UserRoles.
After a bit of trail and error (As I am a beginner in java) I managed to make it work!
CODE:
#FXML
private TextField textUsername;
#FXML
private PasswordField textPassword;
Stage dialogStage = new Stage();
Scene scene;
ResultSet resultSet = null;
//Login for employee
#FXML
private void handleButtonAction(ActionEvent event) {
Database db = new Database();
String username = textUsername.getText();
String password = textPassword.getText();
int usrID = 0;
int roleID = 0;
//String RoleID = EmpSelect.getValue();
String sql = String.format("SELECT * FROM Employee "
+ "WHERE username = '%s' "
+ "and password = '%s' ",
//+ "and RoleID = '%s' ",
username, password);
infoBox("sql [" + sql + "]", "Success", null);
try {
resultSet = db.executeResultSetQuery(sql);
if (!resultSet.next()) {
infoBox("Enter Correct Username and Password", "Failed", null);
} else {
//infoBox("Login Successfull", "Success", null);
resultSet.first();
usrID = resultSet.getInt("idEmployee");
roleID = resultSet.getInt("RoleID");
utilities.setEmployee(usrID, roleID);
FXMLDocumentController controller = new FXMLDocumentController();
utilities.newAnchorpane("EmployeeHomescreen", paneLogin);
infoBox("Login Successfull", "Success", null);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void infoBox(String infoMessage, String titleBar, String headerMessage) {
Alert alert = new Alert(AlertType.INFORMATION);
alert.setTitle(titleBar);
alert.setHeaderText(headerMessage);
alert.setContentText(infoMessage);
alert.showAndWait();
}
So basically what I'm doing here is that an employee of the company can login and it displays the result of the query just so that I know that it works.
import static com.mycompany.mavenproject2.LoginController.infoBox;
import java.net.URL;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
/**
*
* #author John
*/
public class WorkerHomescreenController implements Initializable {
#FXML
private AnchorPane actualmain;
#FXML
private Pane mainpage;
#FXML
private Label label1;
#FXML
private Button but1, but2, but3, but4;
#FXML
private VBox VBPane;
#Override
public void initialize(URL url, ResourceBundle rb) {
//infoBox("User ID = " + utilities.userID, "Success", null);
Database db = new Database();
ResultSet resultSet = null;
String sqlMenu = String.format("SELECT * FROM Menu "
+ "WHERE idMenu IN (SELECT MenuID FROM MenuRoles WHERE RoleID = " + utilities.roleID + ") ");
//+ "AND Active = True");
try {
resultSet = db.executeResultSetQuery(sqlMenu);
int i=0;
GridPane gpnael = new GridPane();
while (resultSet.next()) {
Button button = new Button(resultSet.getString("Link"));
gpnael.add (button, i++, 1 );
button.setStyle("-fx-font: 22 arial; -fx-base: #d81e05; "
+ "-fx-background-radius: 0; -fx-border-width: 1 0 0 0; "
+ "-fx-border-color: white; -fx-font-weight: bold; "
+ "-fx-font-size: 18;");
button.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
try {
resultSet.getURL("Link");
} catch (SQLException ex) {
Logger.getLogger(WorkerHomescreenController.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Utilities utilities = new Utilities();
//Methods to open other pages
#FXML
private void openRequestStatus(ActionEvent event) {
utilities.newPane("RequestStatus", but1, mainpage, label1);
}
#FXML
private void openRegisterMissing(ActionEvent event) {
utilities.newPane("RegisterMissing", but2, mainpage, label1);
}
#FXML
private void openRequestTest(ActionEvent event) {
utilities.newPane("RequestStatus", but3, mainpage, label1);
}
#FXML
private void openRegistertesting(ActionEvent event) {
utilities.newPane("RegisterMissing", but4, mainpage, label1);
}
}
This is the controller of the page where you are redirected to after you login. This page is currently set up in a manner in which based on which RoleId the account you used to login with, it will generate the buttons with the info I have stored in my database.
Utilities controller:
public static int userID;
public static int roleID;
#FXML
public void setEmployee(int idEmployee, int RoleID) {
this.userID = idEmployee;
this.roleID = RoleID;
}
The Utilities controller is used to set the current employee.
My question is this:
My program currently works so that it generates buttons based on your account (Which is good!). What I want to do now is that the buttons have a link saved in the database as well. So that when the buttons are generated, it has a label and a link attached to it so that when you press the button it will go to the link that is attached to the button.
I hope this makes sense.
I know that in a .FXML file if you make a button inside of there you can give it an onAction event which makes it so that if you press the button it takes you to the correct page.
This is what my database looks like:
EMPLOYEE Table
idEmployee firstname lastname username password RoleID
1 John Doe John123 Test123 1
2 Tim Gardener Tim123 Welcome123 2
ROLES Table
idRole roleName
1 Employee
2 Manager
MENU Table
idMenu Name Link
1 but1 RequestStatus
2 but2 RegisterMissing
3 but3 Reports
4 but4 UserRoles
MenuRoles Table
MenuID RoleID
1 1
1 2
2 1
2 2
3 2
4 2
I hope you guys can help me with this problem and thank you for your time I appreciate it!
EDIT 1:
After reading the comment I edit a bit of my code.
The problem I'm having now is that the resultSet in resultSet.getURL("Link"); gives me an error saying: "Local variabel is accessed from within inner class; needs to be declared final.
After making the resultSet final it gives me another error saying
final ResultSet resultSet = null;
This part now gives me an error saying:
resultSet = db.executeResultSetQuery(sqlMenu);
Cannot assign value to final variabel resultSet.
Related
I am a newbie here. First of all I would like to apologize for my bad english. It's not my mother tongue. I haven't used the language for a long time.
I have a problem with my code. I want to display the first row of the column of my database in a text and when I click a button I want that I then get the second row of the column of my database. And so it should go on until I have no more rows to display in that particular column.
So far I've managed to show a row from the database in a "text", but the row is the last row from the database :)
This is the method in the Database class:
public static String deutscheVokAn() {
Connection conn = null;
Statement stmt = null;
String b = null;
try {
conn = DriverManager.getConnection(connString);
String str= "SELECT " + VocabelDeutsch + " FROM " + VocabelTable;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
b = rs.getString(VocabelDeutsch);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
That is the scene in JavaFx and the text "txt" where it should be displayed:
Button zurueck = new Button("Zurück zum Hauptmenü");
Label evl = new Label("Deutsch");
Text txt = new Text();
richtigfalsch = new Label();
txtrichtig = new TextField("");
txtrichtig.setPrefColumnCount(40);
Button weiter = new Button("Weiter");
HBox h1 = new HBox(10, txtrichtig, weiter);
VBox v1 = new VBox(10, zurueck, evl, txt, richtigfalsch, h1);
v1.setPadding(new Insets(5));
Scene scene2 = new Scene(v1, 550, 300);
This is the implementation after you have clicked on the "weiter" (in English: Next) button:
weiter.setOnAction(e -> {
primaryStage.show();
txt.setText(Datenbank.deutscheVokAn());
checkAnswer();
});
I don't know if anyone would want to see the checkAnswer () method as well, but this is what it looks like:
public void checkAnswer() {
if (txtrichtig.getText().equals(Datenbank.englischeVokAn())) {
richtigfalsch.setText("Richtig");
} else {
richtigfalsch.setText("Falsch");
}
}
If someone wants to see the method englishVokAn() here:
public static String englischeVokAn() {
Connection conn = null;
Statement stmt = null;
String b = null;
try {
conn = DriverManager.getConnection(connString);
String str= "SELECT " + VocabelEnglisch + " FROM " + VocabelTable;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(str);
while (rs.next()) {
b = rs.getString(VocabelEnglisch);
}
} catch (Exception e) {
e.printStackTrace();
}
return b;
}
My database class:
public class Datenbank {
private static final String DBlocation = "C:\\Users\\musta\\Vokabeltrainer15_db";
private static final String connString = "jdbc:derby:" + DBlocation + ";create=true";
private static final String VocabelTable = "Vokabel";
private static final String VocabelID = "VokabelID";
private static final String VocabelDeutsch = "VokabelDeutsch";
private static final String VocabelEnglisch = "VokabelEnglisch";
The actual questions are:
Shouldn't I see the second row of the column when I click the Next button? (Apparently not: D)
How could I change my code so that I see the data (1st row, then after clicking the button "weiter" the second row) in this column "VocabelEnglisch" in the text "txt"?
Can someone help me?
Thank you in advance.
I'm writing an application with JavaFX, Scene Builder and SQlite
I have combobox with values(id) that goes from SQLite database.I have 2 textArias. I have a button "Add" that has a method void addCard(ActionEvent event). The method add text from textArias and apply it to particular columns in SQLite.
The problem is: when I try to add values to SQLite and click a button and then I open combobox, I don't see added ID, but when I close the window and open it again combobox display my added id.
It is very annoying to close and open window every time when I want to see the added result in combobox
Model class holds all logic
Controller Class operate between Model and view
Persistent Queries class holds all queries to/from SQLite
How to display new added ID after clicking on the button "Add"?
This video shows how my application work:
Video
Model class:
package src.card;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Cards {
PersistentQueries pq = new PersistentQueries();
final ObservableList OPTIONS = FXCollections.observableArrayList();
Connection connection;
PreparedStatement pst = null;
ResultSet rs = null;
public Cards() {
try {
this.connection = DbConnection.getConnection();
} catch (SQLException ex) {
ex.printStackTrace();
}
if (this.connection == null) {
System.out.println("connection is not successful!");
System.exit(1);
}
}
public ObservableList getOPTIONS() {return OPTIONS;}
//add ID of cards to combobox
void fillCombobox() {
try {
pst = connection.prepareStatement(pq.getSqlSelectID());
rs = pst.executeQuery();
while (rs.next()) {
OPTIONS.add(rs.getString("ID"));
}
pst.close();
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//check if database is connected
public boolean isDbConnected() {
return this.connection != null;
}
}
Controller Class:
package src.card;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import src.card.Cards;
import src.card.Context;
import src.card.DbConnection;
import src.card.PersistentQueries;
import java.net.URL;
import java.sql.*;
import java.util.ResourceBundle;
public class QuestController implements Initializable {
#FXML private TextArea ta_questText, ta_answerText;
#FXML private Label questId, error;
#FXML private ComboBox<String> combobox_question;
Cards cards = new Cards();
PersistentQueries pq = new PersistentQueries();
#Override
public void initialize(URL location, ResourceBundle resources) {
//register QuestController in Context Class
Context.getInstance().setQuestController(this);
cards.fillCombobox();
combobox_question.setItems(cards.getOPTIONS());
}
//adding cards to database
#FXML
void addCard(ActionEvent event) {
if (ta_questText.getText().equals("") ||
ta_answerText.getText().equals("")) {
error.setText("All fields are required!");
} else {
try {
error.setText("");
Connection conn = DbConnection.getConnection();
PreparedStatement stmt = conn.prepareStatement(pq.getSqlInsert());
stmt.setString(1, this.ta_questText.getText());
stmt.setString(2, this.ta_answerText.getText());
ta_questText.setText("");
ta_answerText.setText("");
stmt.execute();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
#FXML
void idList(ActionEvent event) {
questId.setText(combobox_question.getValue() + ".");
}
}
PersistentQueries Class
package src.card;
public class PersistentQueries {
private String sqlInsert = "INSERT INTO Cards(question, answer) VALUES
(?,?)";
private String sqlSelectID = "SELECT ID FROM Cards";
private String sqlSelect = "SELECT question and answer FROM Cards";
public String getSqlInsert() {
return sqlInsert;
}
public void setSqlInsert(String sqlInsert) {
this.sqlInsert = sqlInsert;
}
public String getSqlSelectID() {
return sqlSelectID;
}
public void setSqlSelectID(String sqlSelectID) {
this.sqlSelectID = sqlSelectID;
}
public String getSqlSelect() {
return sqlSelect;
}
public void setSqlSelect(String sqlSelect) {
this.sqlSelect = sqlSelect;
}
}
PROBLEM SOLVED!
in QuestController in the method #FXML void addCard(ActionEvent event) I added
cards.getOBS().clear();
It removes all objects from Observable list
then, I called method from Cards Class that reads all new data from SQLite and add it to Observable list
cards.fillCombobox();
and then I just close all connections:
pst.close();
rs.close();
conn.close();
My rewritten method looks like this:
/adding cards to database, update combobox and clear label text
#FXML void addCard(ActionEvent event) {
if (ta_questText.getText().equals("") || ta_answerText.getText().equals("")) {
error.setText("All fields are required!");
} else {
try {
error.setText("");
Connection conn = DbConnection.getConnection();
pst = conn.prepareStatement(pq.getSqlInsert());
pst.setString(1, this.ta_questText.getText());
pst.setString(2, this.ta_answerText.getText());
pst.execute();
pst = conn.prepareStatement(pq.getSqlSelectID());
rs = pst.executeQuery();
ta_questText.clear();
ta_answerText.clear();
cards.getOBS().clear();
questId.setText("");
cards.fillCombobox();
pst.close();
rs.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
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();
}
I'd like to create a button from one controller by creating an object of that controller but while adding the button to hbox I get a null pointer exception.
Here is my code:
#FXML
private void AddTable1(ActionEvent event)throws Exception
{
List<Button> buttonlist = new ArrayList<Button>();
String sql = "select * from TABLE_NUMBERS";
ResultSet rs = stmt.executeQuery(sql);
int id=1;
while(rs.next())
{
id++;
buttonlist.add(new Button("+tbl_number+"));
}
String tbl_type=combo1.getSelectionModel().getSelectedItem();
String tax = combo2.getSelectionModel().getSelectedItem();
int tbl_number =Integer.parseInt(table_no.getText())+0;
System.out.println(tbl_number);
int max_cap = Integer.parseInt(capa.getText());
String des=desc.getText();
String sql1 ="INSERT INTO Table_Numbers VALUES("+id+",'"+tbl_type+"',"+tbl_number+","+max_cap+",'"+des+"','"+tax+"'"+")";
System.out.println(sql1);
if(!"+table_number+".equals("0"))
{
stmt.execute(sql1);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("TABLE");
alert.setHeaderText(null);
alert.setContentText("SUCCESSFULLY UPDATED");
alert.showAndWait();
// Stage stage = (Stage)Add.getScene().getWindow();
// stage.close();
}
buttonlist.add(new Button("+tbl_number+"));
for(int i=0;i<buttonlist.size();i++)
{
buttonlist.get(i).setMinWidth(120.0f);
buttonlist.get(i).setWrapText(true);
buttonlist.get(i).setMinHeight(40);
}
Button button1 = new Button("+tbl_number+");
RestaurantsController rc=new RestaurantsController();
System.out.println(buttonlist.size());
for(int i=0; i<=buttonlist.size();i++)
{
rc.hbox.getChildren().addAll(buttonlist.get(0));//null pointer exception
}
}
I am writing a simple app to enter user into database & display list of users from database using GWT RPC, Hibernate in Eclipse. The problem I am getting is that the list of users is printed twice on client page.
The reason I found is that as getUser method(i.e. print list) is called on each new entry so that new entries could populate into FlexTable on client page, all entries are populated every time rather. How can I put a check so that only new entries are populated when method is called. OR what could be a better way to achieve what I am trying to do.
Here is my entryPoint code:
package rpctest.client;
import java.util.ArrayList;
import rpctest.shared.User;
import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Rpctest implements EntryPoint {
final TextBox firstName = new TextBox();
final TextBox lastName = new TextBox();
final Button ans = new Button("Add User");
//final Label label1 = new Label("First Name");
//final Label label2 = new Label("Last Name");
private FlexTable userFlexTable = new FlexTable();
//final Label errorLabel = new Label();
private VerticalPanel mainpanel = new VerticalPanel();
private HorizontalPanel addpanel1 = new HorizontalPanel();
private HorizontalPanel addpanel2 = new HorizontalPanel();
private final RpctestServiceAsync callService = GWT
.create(RpctestService.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
userFlexTable.setText(0, 0, "ID");
userFlexTable.setText(0, 1, "First Name");
userFlexTable.setText(0, 2, "Second Name");
userFlexTable.setText(0, 3, "Remove");
//add input boxes to panel
addpanel1.add(firstName);
addpanel1.add(lastName);
firstName.setFocus(true);
//add input/result panels
mainpanel.add(userFlexTable);
mainpanel.add(addpanel1);
addpanel1.add(ans);
ans.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
addStock();
}
});
lastName.addKeyPressHandler(new KeyPressHandler() {
public void onKeyPress(KeyPressEvent event) {
if (event.getCharCode() == KeyCodes.KEY_ENTER) {
addStock();
}
}
});
RootPanel.get().add(mainpanel);
//getUser();
}
private void addStock(){
String name1 = firstName.getValue();
// Stock code must be between 1 and 10 chars that are numbers, letters, or dots.
/*if (!name1.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
firstName.selectAll();
return;
}*/
firstName.setValue("");
String name2 = lastName.getValue();
/*if (!name2.matches("^[0-9A-Z\\.]{1,10}$")) {
Window.alert("'" + name1 + "' is not a valid name.");
lastName.selectAll();
return;
}*/
lastName.setValue("");
firstName.setFocus(true);
callService.addUser(name1,name2,
new AsyncCallback<String>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("check your inputs");
}
#Override
public void onSuccess(String result) {
// TODO Auto-generated method stub
// Add the user to the table.
// int row = userFlexTable.getRowCount();
// userFlexTable.setText(row, 1, result);
getUser();
}
});
}
private void getUser(){
callService.getUser(new AsyncCallback<User[]>() {
public void onFailure(Throwable caught) {
// Show the RPC error message to the user
Window.alert("Problem in database connection");
}
#Override
public void onSuccess(User[] result) {
// TODO Auto-generated method stub
for(int i = 0; i < result.length; i ++)
{
//String s = result[i].getFirstName();
int row = userFlexTable.getRowCount();
userFlexTable.setText(row, 0, result[i].getId().toString());
userFlexTable.setText(row, 1, result[i].getFirstName());
userFlexTable.setText(row, 2, result[i].getLastName());
}
}
});
}
}
I'm not certain if this will work or not, but is it possible to use Session variables and then apply logic based upon the Session state? For instance, the first time getUser() is called, a Session variable could be set indicating it had been called and then logic could be implemented to check if that Session variable has been set or not in subsequent calls...
Kind of thinking out loud but it seems that using Session state might help...