How to refresh vaadin table after altering data? - java

I have this vaadin table which i'm using to display and update records that are being stored in MySQL DB, it all works fine except for updating the table after making a modification or an update, I tried using Table.refreshRowCache() but that wasn't useful
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
java.sql.Statement st = Core.con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery(Core.Show);
while(rs.next()){
table.addItem(new Object[]{rs.getInt(1), rs.getString(2), rs.getDate(3)},rs.getInt(1));
}
}catch(Exception e){
e.printStackTrace();
}
table.addItemClickListener(new ItemClickEvent.ItemClickListener(){
#Override
public void itemClick(ItemClickEvent event) {
Name = new TextField("Name");
Name.setRequired(true);
TextField Name1 = new TextField("Name");
Name1.setVisible(false);
Date = new DateField("Date");
Date.setDateFormat("yyyy-MM-dd");
Date.setRequired(true);
DateField Date1 = new DateField("Date");
Date1.setDateFormat("yyyy-MM-dd");
Date1.setVisible(false);
Id = new TextField();
Id.setVisible(false);
Name.setValue((String) event.getItem().getItemProperty("Name").getValue());
Name1.setValue((String) event.getItem().getItemProperty("Name").getValue());
Date.setValue((Date)event.getItem().getItemProperty("Date").getValue());
Date1.setValue((Date)event.getItem().getItemProperty("Date").getValue());
Save = new Button("Save");
Save.setStyleName("small");
Save.setStyleName("primary");
Save.setSizeUndefined();
Save.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick(ClickEvent event) {
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
Core.stmt = Core.con.prepareStatement(Core.Replace);
Core.statement = Core.con.prepareStatement(Core.ReplaceDate);
Core.stmt.setString(1,Name.getValue().toString());
Core.stmt.setString(2,Name1.getValue().toString());
Core.stmt.setDate(3,new java.sql.Date(Date1.getValue().getTime()));
Core.statement.setDate(1,new java.sql.Date(Date.getValue().getTime()));
Core.statement.setString(2,Name1.getValue().toString());
Core.statement.setDate(3,new java.sql.Date(Date1.getValue().getTime()));
Core.stmt.executeUpdate();
Core.statement.executeUpdate();
Notification.show("done");
Name.setVisible(false);
Date.setVisible(false);
Save.setVisible(false);
Delete.setVisible(false);
}catch(Exception e){
e.printStackTrace();
}
}
});
Delete = new Button("Delete");
Delete.setStyleName("small");
Delete.setStyleName("danger");
Delete.setSizeUndefined();
Delete.addClickListener(new Button.ClickListener(){
#Override
public void buttonClick (ClickEvent ev){
try{
Class.forName("com.mysql.jdbc.Driver");
Core.con = DriverManager.getConnection(Core.db,Core.dbUsername,Core.dbPassword);
Core.stmt = Core.con.prepareStatement(Core.Delete);
Core.stmt.setString(1,Name1.getValue().toString());
Core.stmt.setDate(2,new java.sql.Date(Date1.getValue().getTime()));
Core.stmt.executeUpdate();
Notification.show("done");
Name.setVisible(false);
Date.setVisible(false);
Save.setVisible(false);
Delete.setVisible(false);
}catch(Exception ex){
Notification.show(ex.getMessage());
}
}
});
show.addComponent(Name);
show.addComponent(Date);
Edit.addComponent(Save);
Edit.addComponent(Delete);
show.setSpacing(true);
show.addComponent(Edit);
}
});
As stated in the title I'd apreciate a solution to update the rows after making the modification.

Related

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException ? Please help I don't know what to do [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 1 year ago.
this is my code an di get this error, I don't understand why, I tried multiple times to figure it out what is happening, are you able please to help me. I tried to check the several topic that are around here regarding this but nothing similar found and if I need to do a null check, I am new to this and I don't understand exactly what I need to do
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
public class JavaCrud {
private JPanel Main;
private JTextField txtName;
private JButton saveButton;
private JButton deleteButton;
private JButton updateButton;
private JTextField textField2;
private JTextField txtPrice;
private JTextField txtQty;
public static void main(String[] args) {
JFrame frame = new JFrame("JavaCrud");
frame.setContentPane(new JavaCrud().Main);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
public JavaCrud() {
Connect();
saveButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String name, price, qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
try {
pst = con.prepareStatement("insert into products(pname,price,qty)values(?,?,?)");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.executeUpdate();
JOptionPane.showMessageDialog(null,"Record Addedddddd!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
deleteButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String bid;
bid = textField2.getText();
try {
pst = con.prepareStatement("delete from products where pid = ?");
pst.setString(1, bid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Deleteeeeee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
updateButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String pid,name,price,qty;
name = txtName.getText();
price = txtPrice.getText();
qty = txtQty.getText();
pid = textField2.getText();
try {
pst = con.prepareStatement("update products set pname = ?,price = ?,qty = ? where pid = ?");
pst.setString(1, name);
pst.setString(2, price);
pst.setString(3, qty);
pst.setString(4, pid);
pst.executeUpdate();
JOptionPane.showMessageDialog(null, "Record Updateee!!!!!");
txtName.setText("");
txtPrice.setText("");
txtQty.setText("");
txtName.requestFocus();
textField2.setText("");
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
});
}
Connection con;
PreparedStatement pst;
public void Connect(){
try{
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/gbproducts","root","root");
System.out.println("Success");
}catch(SQLException ex){
ex.printStackTrace();
}
}
}
A NullPointerException is thrown because you adding an addActionListener to your button that has not been instantiated.
In your JavaCrud() method you need to instantiate your buttons.
saveButton = new JButton("SAVE");
deleteButton = new JButton("DELETE");
updateButton = new JButton("UPDATE");
You would also need to instantiate your JTextfield because after a user clicks on a button you are trying to getText() from a JTextField that is null.
Also, it is better to implements ActionListener to your class than to addActionListener to every button. It allows for cleaner code and easier debugging.
Here you can read up on ActionListener Interface

How can I display the data (column) from a database in a text in JavaFX, so that I get the next row from the column after clicking a button?

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.

Adding row in jtable and database using Java

I have a problem with my code and it has no error log so I can't see the problem . . .
Current Problem:
Mainclass() is where the main frame is. . . Clicking ADD will open
AddBroker() and clicking ADD in AddBroker() will update databse and jtable
in MainClass(). Database can now be updated but the jtable in MainClass() won't
change until you open it again
This is my main class (other codes were redacted to focus on problem)
public class MainClass extends JFrame {
JButton button_17 = new JButton("ADD");
button_17.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
//to call class AddBroker()
AddBroker ab = new AddBroker();
ab.setVisible(true);
}
});}
Then this is the class for AddBroker(). . .
public class AddBroker extends JFrame {
JButton btnAdd = new JButton("ADD");
final Object[] addBrokerrow = new Object[3];
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ButtonCon bcd = new ButtonCon();
DriverTableCon dtcd = new DriverTableCon(); //this is just jtable
MainClass mcd = new MainClass();
String a = brokerBroker.getText();
String b = addBroker.getText();
String c = tinBroker.getText();
addBrokerrow[0] = a;
addBrokerrow[1] = b;
addBrokerrow[2] = c;
dtcd.modelBroker.addRow(addBrokerrow);
bcd.addBrokerCon(a,b,c);
}
});}
And ButtonCon() is where the adding of data is
public class ButtonCon {
Connection con;
Statement st;
ResultSet rs;
StringBuffer results;
String url = "jdbc:ucanaccess://C://DATABASE//NTD.accdb";
public void addBrokerCon(String broker, String add, String tin) {
try {
con = DriverManager.getConnection(url);
String sql = "INSERT INTO brokerT (Broker, Address, Tin_No) VALUES (?,?,?)";
ps = con.prepareStatement(sql);
ps.setString(1, broker);
ps.setString(2, add);
ps.setString(3, tin);
ps.executeUpdate();
ps.close();
con.close();
}
catch (Exception e) {
System.out.print(e.toString());
}
} }
There is no error so I have no idea what is wrong here. Any input would be appreciated :)
So it's been a week and what I did try to solve the problem and what I did is add a "Refresh" button that loads the table again.
You fogot about ps.executeUpdate(); between ps.setString(3, tin); and ps.close();.
And remove all with st it is not necessary.

deleting data in java application but it is still displayed in jtable

i have written a java application with tables and functions like add,delete or update.
My problem is, that I delete a row in the table and it is deleted in the database, but when I click on a free space of my JTable the deleted row appears again?
here my code:
DAO CLASS
#Override
public void delete(int id) throws SQLException {
handle = new DatabaseHandler();
con = handle.buildConnectionToServer();
query = "DELETE FROM Team WHERE TID="+id;
std = con.createStatement();
std.execute(query);
con.commit();
handle.closeConnection();
}
CONTROLLER
//ActionListener "Delete" Button in "DeleteEquipment"
public void controllActionListenerDeleteEquipmentSubmit(){
main.setActionListenerDeleteEquipmentSubmit(new ActionListener(){
#Override
public void actionPerformed(ActionEvent arg0) {
if(arg0.getSource()==main.getDeleteEquipment()){
EquipmentDAO equipment = new EquipmentDAO ();
int a = (int)main.getDeleteEquipmentPanel().getDeleteValues().getValueAt(main.getDeleteValues().getSelectedRow(),0);
try {
equipment.delete(a);
JOptionPane.showMessageDialog(null, "Successfully Deleted");
equipmentArr = equipment.show();
main.getDeleteEquipmentPanel().showAllDelete(equipmentArr);
equipmentArr=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
});
}
MAINFRAME
//Back Button of "DeleteEquipment" to "ManageEquipment"
public void setActionListenerBackDeleteEquipment(ActionListener actionListener) {
deleteEquipment.getDeleteEquipmentBack().addActionListener(actionListener);
}
public JButton getDeleteEquipmentBack(){
return deleteEquipment.getDeleteEquipmentBack();
}
//Delete Button in DeleteEquipment
public void setActionListenerDeleteEquipmentSubmit(ActionListener actionListener) {
deleteEquipment.getDeleteEquipment().addActionListener(actionListener);
}
public JButton getDeleteEquipment(){
return deleteEquipment.getDeleteEquipment();
}

Refreshing counter in jLabel

Is there any way to refresh the counter in jLabel when a button
is on click? I tried with repaint(), revalidate() methods already but all does not work.
When like button is on click :
jButton_like.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
int count = 1;
eForumLikeCounter likeAmount = new eForumLikeCounter(
userName, topicId, count);
if (likeAmount.checkLikeAmount() == true) {
JOptionPane
.showMessageDialog(null,
"Unable to perform like on the same thread by the same user");
} else if (likeAmount.checkDislikeExists() == true) {
JOptionPane
.showMessageDialog(null,
"You can only either like or dislike this thread");
} else {
likeAmount.likeCounter();
}
}
});
}
Set up for database :
public void SetUpLikeDislikeAmount() {
int likes = 0;
int dislike = 0;
// Set Up Database Source
db.setUp("IT Innovation Project");
String sql = "Select likeDislike_likes,likeDislike_dislike from forumLikeDislike WHERE likeDislike_topics = "
+ topicId + "";
ResultSet resultSet = null;
// Call readRequest to get the result
resultSet = db.readRequest(sql);
try {
while (resultSet.next()) {
likes += resultSet.getInt("likeDislike_likes");
dislike += resultSet.getInt("likeDislike_dislike");
}
resultSet.close();
} catch (Exception e) {
System.out.println(e);
}
jLabel_like.setText(Integer.toString(likes));
jLabel_dislike.setText(Integer.toString(dislike));
}
Thanks in advance.
Just use the setText() method of the JLabel. Probably something like:
counter.setText("");
or
counter.setText("0");

Categories