Load data to a combo box - java

I have two combo boxes.1 is for main department and other is for sub department. I want to load all the data in Main_department table to combo box. When selecting combo box item i want to load sub_departments relevant to that selected item.
try {
Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT * FROM main_dep";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)maindep.getModel();
while(rst.next()){
dc.addElement(rst.getString(2));
}
} catch (Exception e) {
e.printStackTrace();
}
This is how i got the main Departments. Then i wrote following code for itemStateChange event in main Department combobox.
String main = maindep.getSelectedItem().toString();
Conn c=new Conn();
try {
//Conn c=new Conn();
Statement s=c.createConn().createStatement();
String query ="SELECT Description FROM sub_dep WHERE Main_dep_ID IN (SELECT Main_Dep_Id FROM main_dep WHERE description = '"+main+"')";
ResultSet rst = s.executeQuery(query);
DefaultComboBoxModel dc=(DefaultComboBoxModel)subdep.getModel();
while(rst.next()){
dc.addElement(rst.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
When Main Department is changed sub Departments relevant to that department is loaded to sub Department combobox. But loaded items are Still remaining when another one is selected.
How can i overcome that issue?

But loaded items are Still remaining when another one is selected
You can use:
dc.removeAllElements();
before you start adding new elements to the model.

This case call dependent combo-box.
You have to load data to first combo-box first then, when user select the value of that combo-box, it will cal Ajax or another technology back to server to retrieve data to second combo-box.So , that is idea.
You can see this link for reference here

Related

Displaying data in JTextfield from two different mysql tables

Cheers everyone, beginner here!.
I'm currently working on a Java application to keep track of the inventory in our warehouse. It's all on localhost until it's finished. I've created two tables in MySQL database: one table shows the article code, location and quantity (VOORRAADSYSTEEM); the other table shows article code and description (STAMDATA).
In my GUI, I've got a JTable which loads data from VOORRAADSYSTEEM, and on mouseclickevent (getSelectedRow) shows the data in the corresponding JTextFields (so far so good). The only field not showing is the description field (which should be read from the STAMDATA table).
I've tried creating a method for this specific part of the program. The method runs a query to the second table using a inner join to the first table. Here's the code below.
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(2, sql);
descriptionTxt.setText(rs.getString(sql));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
At this moment I'm not exactly sure how to approach this problem. I'm also going to try using foreign keys. Any help would be appreciated.
There are better ways to handle what you want to do. For instance you could get all the information you need with one query by joining the table on a common column (ARTICLENUMBER and ARTICLECODE) and then display it.
Right now it looks/sounds like you might be trying to get all the information with two queries.
However, there are some errors with your load description method:
private void LoadDescription() {
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/ABEL?zeroDateTimeBehavior=convertToNull", "root", "");
String sql = "SELECT DESCRIPTION FROM VOORRAADSYSTEEM JOIN STAMDATA ON ARTICLECODE = ARTICLENUMBER WHERE ARTICLECODE="+jComboBox1.getSelectedItem();
ResultSet results = conn.createStatment().executeQuery(sql);
if(results.next()) //make sure something was returned to avoid null pointer exception
descriptionTxt.setText(rs.getString("DESCRIPTION"));
else
JOptionPane.showMessageDialog(null, "no results returned");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
This should work a little better for you.

Same code for two jtables but one of them isn't getting values from SQL table

Kindly help me to solve this problem, also tell me how to display data on the table by using condition on comboBox. Following is the code and Output. Please help me, as I have to show this to my instructor tomorrow.
public ArrayList<User> userList() {
ArrayList<User> usersList = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String url="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(url);
String query = "SELECT * FROM tbl_Income";
Statement st=con.createStatement();
ResultSet rs= st.executeQuery(query);
User user;
while(rs.next()){
user= new User(rs.getInt("Amout"),rs.getString("Date"),rs.getString("Source"));
usersList.add(user);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return usersList;
}
public void show_user() {
ArrayList<User> list = userList();
DefaultTableModel model = (DefaultTableModel)Income_Table.getModel();
Object[] row =new Object[3];
for(int i=0;i<list.size();i++){
row[0]=list.get(i).getAmout();
row[1]=list.get(i).getDate();
row[2]=list.get(i).getSource();
model.addRow(row);
}
}
//**********tbl_Expense
public ArrayList<User_E> userList_E() {
ArrayList<User_E> UsersList_E = new ArrayList<>();
try{
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
String eurl="jdbc:sqlserver://localhost:1433;databasename=DB_Project;user=User;Password=password";
Connection con= DriverManager.getConnection(eurl);
String query_E = "SELECT * FROM tbl_Expense";
Statement stt=con.createStatement();
ResultSet rst= stt.executeQuery(query_E);
User_E user_e;
while(rst.next()){
user_e = new User_E(rst.getString("ExpenseDetail"),rst.getString("Category"),rst.getString("Date"),rst.getInt("Amount"));
UsersList_E.add(user_e);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e);
}
return UsersList_E;
}
public void showuser_E(){
ArrayList<User_E> list_E = userList_E();
DefaultTableModel model_e = (DefaultTableModel)Expense_Table.getModel();
Object[] row_e =new Object[4];
for(int i=0;i<list_E.size();i++){
row_e[0]=list_E.get(i).getAmount();
row_e[1]=list_E.get(i).getDate();
row_e[2]=list_E.get(i).getCategory();
row_e[3]=list_E.get(i).getExpenseDetail();
model_e.addRow(row_e);
}
}
This is the Output, getting 0 instead of original data
I cannot tell what the issue by looking at the code posted. But, the application's database access, querying and showing the data in the GUI need to be structured something like this:
1. Access database and get connection:
Get connection object for the database DB_Project (there is no need to create connection objects twice).
2. Query 1:
Create statement
Query the tbl_Income table and populate the "userList"
Close the statement (this also closes the corresponding result set)
3. Query 2:
Create statement
Query the tbl_Expense table and populate the "userList_E"
Close the statement
4. Close connection (this is optional and depends on application requirement).
5. Display GUI using the queried data:
Show user income JTable using the "userList"
Show user expense JTable using the "userList_E"
NOTES:
Place some debug or log statements in the Java code and verify if there is any data in the tables being queried and also what kind of data it is. Querying the database tables directly and interactively or from the command prompt also helps. Also, after populating the list collections print the lists onto the console using System.out.prinltln() statements to verify if the data is populated to them properly.
How to display based on combo box selection:
Here is the link to Java tutorials on using Swing JComboBox - see the section "Handling Events on a Combo Box".
There are different ways one can build the code to acheive this functionality.
By directly querying the database table using the data selected from
the combo box, or
By filtering the data from the "list" data already queried and populated to it. This option requires the queried data from the database tables be stored in instance variables.
Again, it depends upon the application requirement. In case the database table data is not changing then option 2 is the correct method, otherwise query the database table directly.
One hideous thing: nothing is closed (connection, statement, result set).
Try-with-resources may help here, to automatically close those, even on return, break, raised exception.
public ArrayList<User_E> userList_E() {
ArrayList<User_E> usersList_E = new ArrayList<>();
String eurl = "jdbc:sqlserver://localhost:1433;databasename=DB_Project;"
+ "user=User;Password=password";
String query_E = "SELECT * FROM tbl_Expense";
try (Connection con = DriverManager.getConnection(eurl);
Statement stt = con.createStatement();
ResultSet rst= stt.executeQuery(query_E)) {
while(rst.next()){
User user_e = new User_E(rst.getString("ExpenseDetail"),
rst.getString("Category"),
rst.getString("Date"),
rst.getInt("Amount"));
usersList_E.add(user_e);
}
}
catch(SQLException e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
return usersList_E;
}
Class.forName on the driver class is since years no longer required.
For the error: I can only assume that the application is running out of free connections.

How to use a comboBox selection to change the information in the second comboBox

I have created 2 comboBoxes.
The 1st comboBox drop down is created based on a radioButton selection.
The 2nd comboBox drop down list is decided based on the selection made in the 1st comboBox.
The first comboBox pulls its list from a column within one of my SQLite tables.
How can I get the the first comboBox's selection (which is the category column in the table) to cross-reference the selection ID (Cat_ID)?
Example table_1:
Cat_ID Category
1. Test1
2. Test2
In the 2nd comboBox, I want to listen for a selection to be made in the 1st comboBox. Then take the 1st comboBox selection ID (Cat_ID) to query my SQLite database for all entries with the matching ID number on a second table and list them in the 2nd comboBox.
Hopefully this makes sense.
Here is the first comboBox code:
radioButton_1.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
try{
con = DriverManager.getConnection("jdbc:sqlite:WB.db");
con.setAutoCommit(false);
stmt = con.createStatement();
String s = "SELECT * FROM Categories;";
rs = stmt.executeQuery(s);
while(rs.next()){
comboBox.removeItem(rs.getString(2));
comboBox.addItem(rs.getString(3));
}
}
catch (SQLException e){
JOptionPane.showMessageDialog(null, "didnt pull from database");
}finally{
try{
stmt.close();
rs.close();
con.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "ERROR CLOSE");
}
}
}
});

Updating JTable when selecting item in combobox in Java

I coded auto suggesting comboBox that retrieve data from SQL database.It was successful.
Then as next step, I want these functionalities to be done,
*When user select a "ItemID" from the comboBox(When the user type first letter of ItemID, suggest list comes and user can select aItemID - successfully coded), JTable's "ItemID" column and other columns that related to that specific "ItemID" must be updated from the database.
I coded updateTable()method as below;
private void updateTable(){
String existID = (String) IDcombo.getSelectedItem();
String sql = "select * from druginfo WHERE ItemId LIKE '"+existID+"%'";
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
saleTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
} }
Well your tablemodel needs to fire according to the event. If only table data changes then it should fire fireTableDataChanged(). If data and structure both changes then it should fire fireTableStructureChanged(). You can refer to the document
If you're still having trouble with this the one way is to call repaint on your table but that's not a very good way of doing things.

How to set textfield value based on combobox options in Java?

I've a table in database named customer that have attribute like code and name. I've called the value of the customer in other table and displayed it using combo-box. I've displayed the code in combo-box, and all I wanna do is when I choose the code in combo-box, value 'name' can be displayed in text-field , the 'name' appear based on code.
here is my code :
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
cmb_custCode.addItem(rs.getString("custCode"));
txt_custName.setText(rs.getString("custName")); // i'm confused in here, how can i call the name based on the code
}
}
catch(Exception e){
e.printStackTrace();
}
}
for example :
when the code 'B0001' is selected in the combobox, the Jtextfield must also display "Bob" , because code B0001 is belongs to Bob.
EDIT:
Ok. So let's say that you have a user Bob and his code is B001.
ItemStateChanged Method
...
String code = (String) cmb.getSelectedItem();
try{
String sql = "SELECT * FROM customer WHERE code='"+code"'"
PreparedStatement prst = con.prepareStatement();
ResultSet rs = prst.executeQuery(sql);
String name = "";
while(rs.next()){
name = rs.getString('name');
}
txt.setText(name);
}catch(Exception ex){
}
You shouldn't actually connect inside the itemStateChanged but this is just an example.
Take a look at this article. It tells you everything you need to know on how to use combo boxes.
http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html
In your own example code, you can declare the enclosing class as an ActionListener. then use the following after declaring your cmb_custCode
...
cmb_custCode.addActionListender(this);
...
when implementing an ActionListener, you have to implement the method actionPerformed(). I've cribbed the following from : http://docs.oracle.com/javase/tutorial/uiswing/components/combobox.html#listeners but adapted to your code
public void actionPerformed(ActionEvent e) {
JComboBox cb = (JComboBox)e.getSource();
String custCode = (String)cb.getSelectedItem();
updateLabel(custCode);
}
I've maintained the encapsulation of updateLabel(String custCode) from the example on the trail. You can assume that that method is defined as something like :
private void updateLabel(String code) {
txt_custName.setText(map_cust.get(code));
}
I've brough a Map into it with map_cust. It's just a map between code and name, stored in a field
Map<String, String> map_cust = new HashMap<String, String>();
and populated it, this would go in your code, just after retrieving the ResultSet
...
cmb_custCode.addItem(rs.getString("custCode"));
map_cust.put(rs.getString("custCode"), rs.getString("custName");
So, when you get your result set, you populate a map and your combo box, when the client picks and item from the combo box, he fires and actionPerformed, into the registered listener, where the event is manipulated to get the selected item, the String of which is the key to the map_cust, containing mapped key, value pairs, custCode mapped to custName. When that name is pulled from the map, it may be used to update the text of the label.
Here is my code, and it solved my problem. Hope it's useful for you too :).
private void fillText(){
String code = (String) cmb_custCode.getSelectedItem();
try {
Connections con = new Connections();
con.setConnections();
String sql = "select * from customer WHERE custCode='"+code +"'";
Statement stat = con.conn.createStatement();
ResultSet rs=stat.executeQuery(sql);
while (rs.next()){
txt_custName.setText(rs.getString("custName"));
}
}
catch(Exception e){
e.printStackTrace();
}

Categories