I want to add data from mySql database to a table view using observable list as well, using a "Refresh button" that adds new rows to the tableview everytime it is clicked. Here is the code:
public void refreshPage(){
Order curOrder = ordersList.getSelectionModel().getSelectedItem();
ordersList.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
String query = "SELECT orderID, orderStatus, orderTotalCost FROM ORDERS";
try {
DatabaseConnection DBconn = new DatabaseConnection();
connection = DBconn.getDatabaseLink();
// connection = DatabaseConnection.getConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()){
Order newOrder = new Order(resultSet.getString("orderID"), resultSet.getString("orderStatus"), resultSet.getDouble("orderTotalCost"));
orders.add(newOrder);
}
ordersList.setItems(orders);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
refreshPage() is linked to a button on the javaFX stage.
ordersList is the tableView and orders is the observable list.
However, the issue is that when clicking the refresh page button multiple times, it adds the same rows from the data base over and over, I only want it to add unique values to the tableview from the database.
You can use ObservableSet to avoid adding duplicated items.
Create set:
ObservableSet<Order> observableSet = FXCollections.observableSet();
Add new items to set (duplicates will be skipped):
observableSet.add(newOrder);
Im creating an inventory system for our project in school but I stumbled across a problem, I have two forms, when I click the add button in my firstform called mainform, a new form will show the addjframe form, I then put entries, but when I click the add button in the addjframe form the data is in my ms-access database, but my jtable is blank
I tried making my table public static so that it can be called on my second form
heres the code for for my table on the mainform
public static void AddRowToJTable(Object[] dataRow)
{
DefaultTableModel dtm ;
dtm= (DefaultTableModel)jTable1.getModel();
dtm.addRow(dataRow);
dtm.setRowCount(0);
}
heres the code for my add button on the Addjframe form/second form
private void btnaddActionPerformed(java.awt.event.ActionEvent evt) {
String title = txttitle.getText();
String author = txtauthor.getText();
String date = txtdate.getText();
String genre = txtgenre.getText();
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection con = DriverManager.getConnection("jdbc:ucanaccess://D:/elibrary1.accdb");
Statement st = con.createStatement();
st.execute("INSERT INTO libtable(Title,Author,Dateadded,Genre) VALUES ('"+title+"','"+author+"','"+date+"','"+genre+"')");
String sql = "Select * from libtable";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
mainform.AddRowToJTable(new Object[]{rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4)});
}
}
catch (Exception e) {
System.out.print(e.getMessage());
}
}
It should show the entries on my jtable i dont know whats wrong with my code, ive been stuck on this for days, I dont receive any error messages, because the entries are being put in my ms-access database its just that it doesnt show on my jtable
Any help would be appreciated!
here's my first form the table is not showing anything when i click add on my second form
this is my second form to add data in the database
here is my ms-access database showing my recently entered data at the bottom
in a swing button I set a action that it execute delete query and execute another class.
here's my code:
JButton btnScanMyPc = new JButton("SCAN MY PC");
btnScanMyPc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try{
String q="DELETE FROM `search` WHERE 1=1 ";
PreparedStatement st=connection.prepareStatement(q);
ResultSet rs=st.executeQuery();
ReadDir rd = new ReadDir();
ReadDir.main(null);
}
catch(Exception e)
{JOptionPane.showMessageDialog(null, e);}
}
when i execute this query in database it works perfectly. but in java it shows some error like:
java.sql.SQLException: Can not issue data manipulation Statement with executeQuery().
You have to use executeUpdate() instead of executeQuery() for data manipulation like Insert,Update or Delete.
try this one
"DELETE FROM search WHERE 1=1 "
st.executeUpdate(q);
My problem is , while opening a jframe which is including different informations than my main jframe , when i tried to work on this jframe, for example inserting data to SQLite manager's database . But it's giving me Database locked error.I can insert data from my main jframe which i'm opening new jframes with jcombobox. I hink i know source but i dont know how to fix this. I think i need to close my main jframe which i open other frames. So sqlite database can storage this frames datas. Here i'll give to you how can i open jframes with jcombobox and how i'm trying to insert a data to database. Please help me or , leave a comment what're you thinking about this problem. Am i wrong with source idea or true. I need your helps guys. Thanks for reading.
1: This codes how i'm opening jframes with combobox.
public void comboselect(){
int d =ComboBox_name.getSelectedIndex();
if (d==0){
CezalıUye s=new CezalıUye();
s.setVisible(true);
dispose();
}
if(d==1){
DeaktifUye z=new DeaktifUye();
z.setVisible(true);
dispose();
}
if(d==2){
TatbikatForm l=new TatbikatForm();
l.setVisible(true);
dispose();
}
}
2:This codes how i'm trying to insert data which i opened from jcombobox.
private void cmd_saveActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "Insert into cezalitablosu (KimTarafından,Kime,Neden,Kaçıncı,Tarih) values (?,?,?,?,?)";
pst=conn.prepareStatement(sql);
pst.setString(1, jTextField1.getText());
pst.setString(2, jTextField2.getText());
pst.setString(3, jTextField3.getText());
pst.setString(4, jTextField4.getText());
pst.setString(5, jTextField5.getText());
pst.execute();
JOptionPane.showMessageDialog(null, "Kaydedildi!");
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, e);
}
Update_table();
}
execute() can not be use for insert,update and delete.
For insert,update and delete always use
executeUpdate();
The concept of my code is that, it will initially retrieve distinct names from a column 'tname' of my access database table 'try'. It will add those items in a combobox. Once we select an item in the combo box, the data of the row containing tname as the selected item is retrieved and showed in textfields. Then I will make some changes to the text field content. After that, if I click 'Save' button, then all the data of the row containing tname as the selected combobox item must be updated with the new content in the textfields.
Everything goes fine, except the last one. When I click 'save' it considers only the previous text(the one intially retrieved from the database when we select combobox) and not the changes made to it. Kindly help me to diagnose the problem.
Thanks in advance.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.util.Date;
import java.sql.*;
import java.text.*;
public class gut implements ActionListener
{
JComboBox ctn;
JTextField cm,exd,stk,cst,sup,snum,r;
String stn,scm,sexd,sst,scst,ssup,ssnum,sr,icm,iexd,istk,icst,isup,isnum,ir;
JLabel lt,lc,le,ls,lcs,lsp,lspn,lr;
JButton s;
JFrame gp=new JFrame();
public gut()
{
gp.setSize(500,500);
gp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gp.setLayout(null);
lt=new JLabel("Tablet Name",JLabel.RIGHT);
lc=new JLabel("Composition",JLabel.RIGHT);
le=new JLabel("Expiry Date (dd/mm/yyyy)",JLabel.RIGHT);
ls=new JLabel("Stock",JLabel.RIGHT);
lcs=new JLabel("Cost",JLabel.RIGHT);
lsp=new JLabel("Supplier",JLabel.RIGHT);
lspn=new JLabel("Supplier Number",JLabel.RIGHT);
lr=new JLabel("Rack",JLabel.RIGHT);
lt.setBounds(100,120,120,20);
lc.setBounds(100,140,120,20);
le.setBounds(60,160,160,20);
ls.setBounds(100,180,120,20);
lcs.setBounds(100,200,120,20);
lsp.setBounds(100,220,120,20);
lspn.setBounds(100,240,120,20);
lr.setBounds(100,260,120,20);
ctn=new JComboBox();
cm=new JTextField();
exd=new JTextField();
stk=new JTextField();
cst=new JTextField();
sup=new JTextField();
snum=new JTextField();
r=new JTextField();
ctn.setBounds(240,120,120,20);
cm.setBounds(240,140,120,20);
exd.setBounds(240,160,120,20);
stk.setBounds(240,180,120,20);
cst.setBounds(240,200,120,20);
sup.setBounds(240,220,120,20);
snum.setBounds(240,240,120,20);
r.setBounds(240,260,120,20);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select DISTINCT tname from try");
while(rs.next())
{
ctn.addItem(rs.getString("tname"));
}
conn.close();
}
catch(Exception e)
{
}
gp.add(lt);gp.add(ctn);
gp.add(lc);gp.add(cm);
gp.add(le);gp.add(exd);
gp.add(ls);gp.add(stk);
gp.add(lcs);gp.add(cst);
gp.add(lsp);gp.add(sup);
gp.add(lspn);gp.add(snum);
gp.add(lr);gp.add(r);
ctn.addActionListener(this);
s=new JButton("Save");
s.setBounds(200,300,100,20);
gp.add(s);
s.addActionListener(this);
gp.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
String act=evt.getActionCommand();
String scb=(String)ctn.getSelectedItem();
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
Statement st=conn.createStatement();
ResultSet rs=st.executeQuery("select * from try where tname='"+scb+"'");
SimpleDateFormat formatter=new SimpleDateFormat("dd/MM/yyyy");
while(rs.next())
{
icm=rs.getString("composition");
iexd=formatter.format(rs.getDate("exdate"));
istk=Integer.toString(rs.getInt("stock"));
icst=rs.getString("cost");
isup=rs.getString("sup");
isnum=rs.getString("supnum");
ir=rs.getString("rack");
}
cm.setText(icm);
exd.setText(iexd);
stk.setText(istk);
cst.setText(icst);
sup.setText(isup);
snum.setText(isnum);
r.setText(ir);
conn.close();
}
catch(Exception e)
{
System.out.println(e);
}
if(act.equals("Save"))
{
scm=cm.getText();
sexd=exd.getText();
sst=stk.getText();
scst=cst.getText();
ssup=sup.getText();
ssnum=snum.getText();
sr=r.getText();
System.out.println(scm+","+sexd+","+sst+","+scst+","+ssup+","+ssnum+","+sr);
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn=DriverManager.getConnection("jdbc:odbc:vasantham","","");
PreparedStatement ps=conn.prepareStatement("UPDATE try set composition=?,exdate=?,stock=?,cost=?,sup=?,supnum=?,rack=? where
tname=?");
ps.setString(1,scm);
ps.setString(2,sexd);
ps.setString(3,sst);
ps.setString(4,scst);
ps.setString(5,ssup);
ps.setString(6,ssnum);
ps.setString(7,sr);
ps.setString(8,scb);
ps.executeUpdate();
JOptionPane.showMessageDialog(null,"Your entry has been stored successfully!!!");
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null,"Error!Try again!");
System.out.println(e);
}
}
}
public static void main(String[] args)
{
new gut();
}
}
On top of what everybody else has already said, if you REALLY want to use a single action listener, you are going to need to work out which action has actually occurred.
You could check the source of the ActionEvent (evt.getSource()) or, more appropriately, you could assign a action command to each component using the action listener.
Check out JComboBox.setActionCommand(...) and JButton.setActionCommand(...)
After that, it's a simple case of checking the ActionEvent.getActionCommand() property to determine the correct action to take.
The problem is that every time you hit the "Save" button you are retrieving the information from the database over again, so, you overwrite the TextFields and then you read from the TexFields content. Try to take out this part:
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection
("jdbc:odbc:vasantham", "", "");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("select * from try where tname='"
+ scb + "'");
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
while (rs.next()) {
icm = rs.getString("composition");
iexd = formatter.format(rs.getDate("exdate"));
istk = Integer.toString(rs.getInt("stock"));
icst = rs.getString("cost");
isup = rs.getString("sup");
isnum = rs.getString("supnum");
ir = rs.getString("rack");
}
cm.setText(icm);
exd.setText(iexd);
stk.setText(istk);
cst.setText(icst);
sup.setText(isup);
snum.setText(isnum);
r.setText(ir);
conn.close();
} catch (Exception e) {
System.out.println(e);
}
from the action performed method.
Every time your action event is fired, you read data from DB and write it into the textfields.
You can change that text and it will be displayed correctly in your textfields. But when you click save, all your changes are overwritten with the DB values again.
So you have to separate the functionalities "read from DB" and "write changes".
edit:
oops, too slow..
Your actionPerformed() function retrieves the information from the database every time. If you press the Save button it will first retrieve the information and then save the information if the action command is "Save". This is why you always get the information that's currently in the database from getText() when pressing the Save button.
Make a different function / actionListener to execute when the Save button is pressed or take the part of the code that updates the text fields else where.
Try something like this instead:
JButton saveButton = new JButton( new AbstractAction("save") {
#Override
public void actionPerformed( ActionEvent e ) {
// Save the info here or just call a function that will.
}
});