Change the value of JComboBox and JTextfield every time the mouse clicked? - java

How can I properly change the value of my Swing Controls like JComboBox and JTextfields every time I click the cells of my JTable which is my data? What I want to do if there are more than one record that has the same first letter of the I selected. Will change the value every time I click based on their row position?
Screenshot
When I clicked one of the values in the JTable it shows the current value in the JTextfield and JComboBox but If I click a again it didn't change? Any help?
SELECT (For retrieving)
private void SearchButtonActionPerformed(java.awt.event.ActionEvent evt) {
String searchSection = Section_SearchSection_Textfield.getText();
String searchSECTIONSETTINGS = "SELECT allsections_list.SECTION_ID, allsections_list.SECTION_NAME, allsections_settings.ADVISER_ASSIGNED, allsections_settings.SECTION_POPULIMIT, allsections_settings.ROOM_ASSGN,\n" +
"allsections_settings.YRLEVEL_ASSGN,allsections_settings.SCHOOL_YEAR,allsections_settings.SESSION_ASSIGNED\n" +
"FROM allsections_list\n" +
"RIGHT JOIN allsections_settings\n" +
"ON allsections_list.SECTION_ID = allsections_settings.SECTION_ID\n" +
"WHERE SECTION_NAME LIKE ?";
try (Connection myConn = DBUtil.connect();
PreparedStatement myFirstPs = myConn.prepareStatement(searchSECTIONSETTINGS);)
{
myFirstPs.setString(1, '%'+searchSection+'%' );
try (ResultSet myFirstRs = myFirstPs.executeQuery();)
{
sectionJTable.setModel(DbUtils.resultSetToTableModel(myFirstRs));
int result = 0;
while (myFirstRs.next())
{
String myName = myFirstRs.getString(2);
System.out.println(myName);
result++;
}
}//end of try myFirstRs (ResultSet)
}//end of try myFirstPs (PreparedStatement)
}
JTable (MouseClicked)
private void sectionJTableMouseClicked(java.awt.event.MouseEvent evt) {
if (evt.getClickCount() == 1) {
final JTable target = (JTable)evt.getSource();
final int row = target.getSelectedRow();
final int column = target.getSelectedColumn();
// Cast to ur Object type
Object value = target.getValueAt(row,column);
JOptionPane.showMessageDialog(null, value);
String selectSections = "SELECT * FROM allsections_list a JOIN allsections_settings b ON b.SECTION_ID = a.SECTION_ID";
try (Connection myConn = DBUtil.connect();
PreparedStatement myPs = myConn.prepareStatement(selectSections);)
{
try (ResultSet myRs = myPs.executeQuery())
{
int resultCounter = 0;
while(myRs.next())
{
Section_SectionName_TextField.setText(myRs.getString("SECTION_NAME"));
Section_Student_Limit_ComboBox.setSelectedItem(myRs.getString("SECTION_POPULIMIT"));
Section_Room_Assignment_ComboBox.setSelectedItem(myRs.getString("ROOM_ASSGN"));
Section_Student_Limit_ComboBox1.setSelectedItem(myRs.getString("ADVISER_ASSIGNED"));
Section_Session_Settings_ComboBox.setSelectedItem(myRs.getString("SESSION_ASSIGNED"));
Section_Session_Level_ComboBox.setSelectedItem(myRs.getString("YRLEVEL_ASSGN"));
Section_SchooYear_ComboBox.setSelectedItem(myRs.getString("SCHOOL_YEAR"));
resultCounter++;
}
}
}
}
When I try to add System.out.print(myRs.getString("SECTION_NAME")); in my second Result Set it prints out all the values of my SECTION_NAME not the current that I selected.

I think I found the problem:
while(myRs.next())
{
Section_SectionName_TextField.setText(myRs.getString("SECTION_NAME"));
Section_Student_Limit_ComboBox.setSelectedItem(myRs.getString("SECTION_POPULIMIT"));
Section_Room_Assignment_ComboBox.setSelectedItem(myRs.getString("ROOM_ASSGN"));
Section_Student_Limit_ComboBox1.setSelectedItem(myRs.getString("ADVISER_ASSIGNED"));
Section_Session_Settings_ComboBox.setSelectedItem(myRs.getString("SESSION_ASSIGNED"));
Section_Session_Level_ComboBox.setSelectedItem(myRs.getString("YRLEVEL_ASSGN"));
Section_SchooYear_ComboBox.setSelectedItem(myRs.getString("SCHOOL_YEAR"));
resultCounter++;
}
In the above part you are setting all records to the your components in a while statement. So components will show only the last record, in this case "Gold".
But actually there is no need to querying database in sectionJTableMouseClicked. You can get all values by getValueAt and set to the components.

Related

How check whether a particular data exits in column

I am working on java swing project with database. There is a search by option (dropdown) to select by which attribute the user want to search and very next to dropdown their is a textfield where user can enter value and then click search. now i want to search for that particular value in that particular column(which is selected by user through the dropdowm) if it is exits i want to print them "found" if not then i want to display not found message.. Please find the attached images & code below.
For example: from dropdown if user select 'customer id' which is a column name and they enter id in the textfiled as '123456' then if it is exits in the column then i need to print found message else i need to print not found.
String column = jcombo2.getSelectedItem().toString();
String value = key.getText();
DefaultTableModel model = (DefaultTableModel) customerinfo.getModel();
DefaultTableModel model2 = (DefaultTableModel) customerinfo.getModel();
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs =st.executeQuery(mysqlQuery);
while(rs.next()) {
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
Try this:
String mysqlQuery = "SELECT COUNT(*) FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
if (rs.next() && (rs.getInt(1) != 0))
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
st.close();
Or in case you want to fill the table with found items contemporarily:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
found_it = true;
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (found_it)
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
Same as before but printing the 'found it' directly after having found the first element:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
if (!found_it)
{
printFoundIt(); // or whatever you want to do
found_it = true;
}
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (!found_it)
printDidntFindIt(); // or whatever you want to do

How to delete row from bound JTable?

I have a JTable bound to MySQL. I already have done code to insert data.
But i don't know how to delete.
I have this sample delete method that works in other simple projects.
public String deleteItem(String name) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where name = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, name);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Even when I worked with an unbound table I have done this remove row from jtable that did well for me.
But now its a table bound to MySQL and I can't find a way to delete row... already searched on the internet. Found nothing.
PS: i'm using netbeans. i right-clicked jtable > bind > elements , to bind table.
Oh, I found a way!
First, I changed my deleteItem method, to delete by id
ItemDAO.java
public String deleteItem(int ID_item) {
String answer = "";
try {
Connection con = Connect.getConnection();
String sql = "Delete FROM item where ID_Item = ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, ID_item);
ps.executeUpdate();
ps.close();
con.close();
answer = "OK";
} catch (Exception e) {
answer = e.toString();
}
return answer;
}
Then the action in delete button goes like this.
Form.java
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
int column = 0; // get the first column which is ID_Item
int row = tableItem.getSelectedRow(); //get row selected by user
int value = (int) tableItem.getModel().getValueAt(row, column); // store ID_Item value
String answer = new ItemDAO().deleteItem(value); // call up deleteItem method
if(answer.equals("OK")) {
System.out.println("OK"); // just for test
itemList.clear(); // this is needed to update the bound table after Insert/Delete/Update etc
itemList.addAll(itemQuery.getResultList()); // same as above comment
}else{
System.out.println("ERROR"); // just for test.
}
Maybe isn't the most beautiful way to do it, but it works.

Cannot update multiple times using for loop

I have a form that borrows stocks from branchA to branchB. The user can input multiple products and I do this by having a text area split it with (","), and place in it an array. After submitting my form, I insert it in a table and then update the stocks from another table. Here is my code (which I actually placed in a JSP file instead of a normal Java class):
try {
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS (control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to) values ('"+cn+"','"+po+"','"+idsplit[iCtr]+"','"+issplit[iCtr]+"','"+qtsplit[iCtr]+"','"+fr+"','"+to+"')";
pInsertPullout = conn.prepareStatement(sInsertQuery);
pInsertPullout.executeUpdate();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateFrom.executeBatch();
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
pUpdateTo.executeBatch();
} }
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
The first query successfully inserts multiple rows in the table but my second query only updates the first index from the array. I don't know what I could be doing wrong since they're both inside the same loop.
Any help please?
UPDATE: I did this .addBatch and .executeBatch and it work a while, now it doesn't work again. It only updates the first index.
Try something like this snippet (i might ve messed up with types of your variables, because I guessed them.
try {
sInsertQuery = "INSERT INTO PULLOUT_REPORTS " +
"(control_number, dateofpullout, item_des, item_size, item_qty, pullout_from, pullout_to)" +
" values " +
"(?,?,?,?,?,?,?)";
pInsertPullout = conn.prepareStatement(sInsertQuery);
sUpdateRecord = "UPDATE maintable SET antip_qty = antip_qty - ? WHERE item_code = ? AND item_size = ?";
pUpdateFrom = conn.prepareStatement(sUpdateRecord);
sUpdateRecord1 = "UPDATE maintable SET binang_qty = binang_qty + ? WHERE item_code = ? AND item_size = ?";
pUpdateTo = conn.prepareStatement(sUpdateRecord1);
for (int iCtr=0; iCtr<idsplit.length; iCtr++) {
pInsertPullout.setLong(1, cn);
pInsertPullout.setLong(2, po);
pInsertPullout.setString(3, idsplit[iCtr]);
pInsertPullout.setString(4, issplit[iCtr]);
pInsertPullout.setString(5, qtsplit[iCtr]);
pInsertPullout.setString(6, fr);
pInsertPullout.setString(7, to);
pInsertPullout.executeUpdate();
pInsertPullout.clearParameters();
if (fr.equals("Antipolo") && to.equals("Binangonan")) {
pUpdateFrom.setString(1,qtsplit[iCtr]);
pUpdateFrom.setString(2,idsplit[iCtr]);
pUpdateFrom.setString(3,issplit[iCtr]);
pUpdateFrom.addBatch();
pUpdateTo.setString(1,qtsplit[iCtr]);
pUpdateTo.setString(2,idsplit[iCtr]);
pUpdateTo.setString(3,issplit[iCtr]);
pUpdateTo.addBatch();
}
}
pUpdateFrom.executeBatch();
pUpdateTo.executeBatch();
}
catch (Exception e) {
response.sendRedirect("error.jsp");
}
and don't forget to cleanup resources afterwards. Close statements and connection in finally{} clause.

Java Netbeans fetching query result into JLabels

I have a JFrame form which asks the user to insert for example his name then it shows him the addresses of all houses he owns (user may own more than one house).
However, since i dunno how many result the query will come out with, i created a function of type vector and stored the data into it, then returned the vector. At the JFrame form i'm doing something like this.
Vector<String> data = User.getHouse(userName.getText());
if (data.isEmpty()) {
JOptionPane.showMessageDialog(null, "No Houses were found!");
}
else {
for(int i=0; i<data.size(); i++)
{
System.out.println(data.elementAt(i));
houses.setText(data.elementAt(i));
houses2.setText(data.elementAt(i+1));
}
}
the function code:
public static Vector<String> getHouse(String playerName) throws SQLException, ClassNotFoundException {
Connection con = DBConnect.getConnection();
PreparedStatement getId = con.prepareStatement("SELECT Player_Id from PLAYERS WHERE Name = ?");
getId.setString(1, playerName);
ResultSet y = getId.executeQuery();
if(y.next())
{
id = y.getString("Player_id");
System.out.println("playerID => " + id);
}
System.out.println("playerName => " + playerName);
PreparedStatement s = con.prepareStatement("SELECT House_Name FROM HOUSES WHERE Player_Id = ?");
s.setString(1, id);
System.out.println("getHouse => Query");
ResultSet x = s.executeQuery();
Vector<String> data = new Vector<String>();
while(x.next())
{
data.addElement(x.getString("House_Name"));
}
return data;
}
(query returns 2 rows). How can i correctly set the JLabel text with the query result?

ResultSet returns only last row into JTable

I have done enough searches to solve my problem which i have done partly but there's this one bug that keeps disturbing me.I am trying to fetch data from a database based on a condition.I have a table 'user_branch' with a foreign key column branchID which is supposed to fetch the coresponding branchNames in another table 'branches' and I am supposed to display the results into a JTable.When i do System.out.println i get all my results but it returns only the last row when i display in a JTable(branchJTable).This is the code i am using
int row = user2BAssignedJTable.getSelectedRow();
assignUserID.setText(user2BAssignedJTable.getModel().getValueAt(row, 0).toString());
user2BAssignedField.setText(user2BAssignedJTable.getModel().getValueAt(row, 1).toString());
try {
String userBrQry = "SELECT branchID FROM user_branch WHERE userID IN(?) ";
String brQ = "SELECT branchName FROM branches WHERE branchID IN(%s) ";
pstmt = con.prepareStatement(userBrQry);
pstmt.setString(1, assignUserID.getText());
results = pstmt.executeQuery();
results.last();
int nRows = results.getRow();
results.beforeFirst();
while (results.next()) {
String branchIDS = results.getString("branchID");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < nRows; i++) {
builder.append("?");
if (i + 1 < nRows) {
builder.append(",");
}
}
brQ = String.format(brQ, builder.toString());
PreparedStatement ps = con.prepareStatement(brQ);
for (int i = 0; i < nRows; i++) {
ps.setString(i + 1, branchIDS);
}
ResultSet rs = ps.executeQuery();
//branchJTable.setModel(DbUtils.resultSetToTableModel(rs));
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
while (rs.next()) {
String branchname = rs.getString("branchName");
model.addRow(new Object[]{branchname});
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
Forget about the first 3 rows as it is a another JTable event i use to get the userID to use as a condition for getting a particular user's branches assigned to him.
The branches assigned to a user is dynamic hence using StringBuilder.
I am supposed to display the results into another JTable called branchJTable which only displays the last row.Any HELP would be appreciated!
From your question, I think you should declare the JTable
javax.swing.table.DefaultTableModel model = new javax.swing.table.DefaultTableModel();
model.setColumnIdentifiers(new String[]{"Branch Name"});
branchJTable.setModel(model);
before your first loop -
i.e. before while (results.next()) { in your code.
Otherwise in loop, for each loop execution,
the JTable Model is initialising and you are getting the last inserted row in Jtable.

Categories