Autofill a textfield when clicking a value in jComboBox - java

Good evening all!
I've been working on a simple warehouse/inventory management system which is connected to a mySql database. One of the tables in that database (OESCODE) has information about which area ("AREA") of the warehouse an article is in, and a corresponding numeric value ("CODE"). Example, small goods would be 1, long goods would be 2 etc etc.
In the GUI, i've a jCombobox that allows you to select the area, and the idea is to have a textfield below display the corresponding numeric value.
Here's a screenshot of what I mean:
Screenshot 1
It's the fields labeled Hal (halCombo) and OES (oesTxt) Code.
The corresponding code:
private void pickHalComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String fill = (String) halCombo.getSelectedItem();
String query = "SELECT * FROM OESCODE WHERE AREA=?";
try {
pst = conn.prepareStatement(query);
pst.setString(1, fill);
rs = pst.executeQuery();
if (rs.next()) {
String code = rs.getString("CODE");
oesTxt.setText(code);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Here's the catch though: the fields above (labeled Artiekelcode, Omschrijving and Eenheid) do EXACTLY the thing i'm describing above. Example, when i click a value in the Artiekelcode field, the Omschrijving and Eenheid fields get autofilled with the corresponding values (from a different database table, ofcourse).
Here's the code for that:
private void pickArticleComboPopupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
String fill = (String) pickArticleCombo.getSelectedItem();
String query = "SELECT * FROM STAMDATA WHERE ARTIKELNUMMER=?";
try {
pst = conn.prepareStatement(query);
pst.setString(1, fill);
rs = pst.executeQuery();
if (rs.next()) {
String desc = rs.getString("OMSCHRIJVING");
String eenh = rs.getString("EENHEID");
eenheidTxt.setText(eenh);
pickDescriptionTxt.setText(desc);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
So for the past hours, I've been trying to figure out why it works on the fields above and not on the fields below, since both principles are the same.
Any thoughts would be highly appreciated.
Thanks in advance!

Related

Getting Multiple Data using Text field + Jbutton from SQL Server to Jtable

Good day, just wanna ask. I have a Java GUI where I want to add multiple data from SQL server to my Jtable. The flow here is that I would want to use the text field as search field where I will add the info for searching and use the Jbutton to perform the search action then it will give/show me the data to my Jtable. Actually the code is running however some of the data like the 1st data added to my SQL serve and from data id 7 and and up are not showing. How would I fix this and show multiple data with same order ID form SQL server?
Thank you!!
try {
String query = "select * from `sales_product` where order_id = ?";
pst = con.prepareStatement(query);
pst.setString(1, txsearch.getText());
ResultSet rs = pst.executeQuery();
if(rs.next()) {
while(rs.next()) {
String prodname = rs.getString("prodname");
String price = String.valueOf(rs.getInt("price"));
String qty = String.valueOf(rs.getInt("qty"));
String total = String.valueOf(rs.getInt("total"));
model = (DefaultTableModel) datatable.getModel();
model.addRow(new Object[]{
prodname,
price,
qty,
total
});
int sum = 0;
for (int a = 0; a < datatable.getRowCount(); a++) {
sum = sum + Integer.parseInt(datatable.getValueAt(a, 3).toString());
}
Ltotal.setText(Integer.toString(sum));
}
}
else {
JOptionPane.showMessageDialog(this, "No order found!");
txsearch.setText("");
}
} catch (SQLException ex) {
Logger.getLogger(milktea.class.getName()).log(Level.SEVERE, null, ex);
}
}
if(rs.next()) {
while(rs.next()) {
No need for the if (rs.next()) statement. That is causing you to skip the first row of data in the ResultSet.
All you need is the while (rs.next()) statement to create the loop to read all rows in the ResultSet.

JComboBox error blocking another field display

I have a problem with JComboBox. It's blocking another field in a frame meant to display another value that is linked through a foreign key in a database, a value that depends on the combo box already pop out. But somehow, after the user clicks the combo box it is blocking another field. The app is using MySql.
Here's the code:
ComboBox method to fill value from DB
public void comboBoxBerat(){
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
try {
sql = "SELECT * FROM weight_of_services";
rs = stat.executeQuery(sql);
while (rs.next()) {
jComboBoxBerat.addItem(rs.getString("weight"));
}
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, e.getMessage());
}
}
Action when selection is made from combo box, its get the value that linked with foreign key
private void jComboBoxBeratActionPerformed(java.awt.event.ActionEvent evt) {
DbConnection DB = new DbConnection();
DB.DbConnection();
con = DB.con;
stat = DB.stmt;
String item = (String)jComboBoxBerat.getSelectedItem();
String sql = "SELECT price FROM weight_of_services WHERE weight = ?";
try {
pst = con.prepareStatement(sql);
pst.setString(1, item);
rs = pst.executeQuery();
if (rs.next()) {
String price = rs.getString("price");
txtHargaBerat.setText(price); //put value from combobox to txtField
}
con.close();
} catch (Exception e) {
}
}
The problem after I select from the box its blocking another field.
This is the combo box problem in the frame
It's solved. This because i am using jpanel for customizing color for the frame. Its just so messed up with the stacking one panel on top of the other one. That's why my dropdown list get blocked. So what I did, removed all the panel. Custom and sorting it more carefully and tidy from the start.

Problem populating a Jlist based on two Jcomboboxes connected to a PostgreSQL database

Good afternoon
I'm working on a project in witch I have to calculate the performance of a pump for certain parameters like rotation, number of stages, diameter and viscosity. At first I created a database using PostgreSQL with several commercial pumps. The database contains schemas as the companies that manufacture the pumps, in each schema there are tables representing the different series of pumps and the tables have several pumps organized as lines. The lines contains coefficients that represent the pumps and that are necessary to calculate the performance.
I tried to code the application in C++, but was too hard to connect with Postgre, so I ended working with Java and Netbeans (I think it's easier to newcomers). The application is running quite good so far, but I have found two problems that I cannot solve.
To select the pump to make the calculations I had to use two Jcomboboxes and a Jlist. The first Jcombobox is for selecting the manufacturer, the second to select the serie. Finally, the Jlist displays all the pumps in that serie so the user can select one.
I was able to populate the first Jcombobox with the schemas of the database (thanks to you guys, actually), the second with the tables of the schema selected in the first and the Jlist with the names of the pumps.
The first problem is that I cannot clear the second Jcombobox (the series one) after changing the selected manufacturer in the first Jcombobox, it will add more itens every time that I change the first Jcombobox, even if I re-select an item that was already selected. I tried using the command "removeAllItems()", but then it displays just one table and stop filling the Jcombobox.
The second problem is that, when I select a serie in the second Jcombobox, it doesn't immediately display the pumps in the Jlist, the Jlist starts displaing after I select another serie. So, I have to select one and then change to another so the pumps start appearing in the Jlist.
I'm sorry for the long text and the english errors, I hope its enough for you guys to understand. I know the code is not pretty, that's because I'm not so good at this yet and I'm in a bit of a hurry to deliver it.
Here is the code, without all the generated code that Netbeans does.
public final class LabPump extends javax.swing.JFrame {
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
public LabPump() {
initComponents();
con = ConnectPump.connect();
FillSelectFabricante();
}
public void FillSelectFabricante(){
try {
rs = con.getMetaData().getSchemas();
while(rs.next()){
String schemas = rs.getString("TABLE_SCHEM");
if(schemas.equals("information_schema") || schemas.equals("pg_catalog")){
}
else{
selectFabricante.addItem(schemas);
}
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillSelectSerie(String fabricante){
//selectSerie.removeAllItems();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
while(rs.next()){
String tables = rs.getString(3);
selectSerie.addItem(tables);
}
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
public void FillListBomba(String fabricante, String serie){
DefaultListModel dlm = new DefaultListModel();
dlm.removeAllElements();
try{
String sql = "select * from " + fabricante + "." + serie;
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String bomba = rs.getString("bomba");
dlm.addElement(bomba);
}
listBomba.setModel(dlm);
}
catch(SQLException error){
JOptionPane.showMessageDialog (null,error);
}
}
private void selectSerieActionPerformed(java.awt.event.ActionEvent evt) {
selectSerie.addActionListener((ActionEvent e) -> {
String fabricante = selectFabricante.getSelectedItem().toString();
String serie = selectSerie.getSelectedItem().toString();
FillListBomba(fabricante, serie);
});
}
private void selectFabricanteActionPerformed(java.awt.event.ActionEvent evt) {
String fabricante = selectFabricante.getSelectedItem().toString();
FillSelectSerie(fabricante);
}
Thank you all.
I managed to solve the problem just now. When the selectSerie.removeAllItems() line was uncommented the program returned a NullPointerException error.
To solve the problem I used the DefaultComboBoxModel class and then used the RemoveAllElements() method. I'm not quite sure why the other method didn't work though.
Thanks for your time and help Peter.
public void FillSelectSerie(String fabricante) {
DefaultComboBoxModel box;
box = new DefaultComboBoxModel();
box.removeAllElements();
try {
String[] sql = {"TABLE"};
rs = con.getMetaData().getTables(null, fabricante, "%", sql);
box.addElement("-");
while (rs.next()) {
String tables = rs.getString(3);
box.addElement(tables);
}
selectSerie.setModel(box);
} catch (SQLException error) {
//JOptionPane.showMessageDialog (null,error);
}
}

Get next record from SQLite database when button is clicked

I have read notes about this but none seems to work for me. I have an SQLite database and with Netbeans as my IDE, I have a jframe that displays data records in a jtable, with records displayed in ascending order. Clicking on a record displays them in jtextfields.
I want to move to next record in database in ascending order when I click on a button, but it doesn't seem to work. What am I doing wrong?
try{
String sql ="select * from Employees order by Name ASC";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
int i = rs.getInt("ID");
String idi= Integer.toString(i);
id.setText(idi);
String a = rs.getString("Name");
name.setText(a);
String b = rs.getString("Contact");
contact.setText(b);
String c = rs.getString("Email");
email.setText(c);
String d = rs.getString("Residence");
residence.setText(d);
String e = rs.getString("Job_Type");
comboJob.setSelectedItem(e);
}
else {
rs.previous();
}
}
catch(SQLException | HeadlessException ex)
{
JOptionPane.showMessageDialog(null, ex);
}finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
}
}
you need to store the values from database in an array and then iterate over it with your (prev,next) button like
i=0;
while(rs.next()) {
dataset["ID"][i]=Integer.toString(rs.getInt("ID"));
dataset["Name"][i]=rs.getString("EName");
i++
}
to display information you can use dataset array like
id.setText(dataset["ID"][i]);
name.setText(dataset["EName"][i]);
not checked syntax but the logic is correct.

cardinality violation and NullPointerException while populating a combobox with available courses

I am relativity new to java programming any way here what i am trying to do
I am trying to populate combobox1(Add list) with the courses available to the student and then removing the selected item and sending to combobox2(drop list)
but its simply not reacting right especially when the student doesn't have any courses that are available to add and it returns the exceptions
"net.ucanaccess.jdbc.ucanaccessSQLException:cardinality violation"
&
"java.lang.NullPointerException"
here's how initialize each of the comboboxes
try
{String mail=Login.user_mail;
String sql = "select CourseCode from Course where CourseCode!=(select CourseCode from CourseStudent where StudentEmail='"+mail+"') OR NOT EXISTS(select CourseCode from CourseStudent where StudentEmail='"+mail+"')";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox1.setModel(m);
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null, ex.toString());
}
then combo box2
String mail=Login.user_mail;
String sql = "select CourseCode from CourseStudent where StudentEmail='"+mail+"'";
java.sql.ResultSet rs = dbm.select(sql);
DefaultComboBoxModel m = new DefaultComboBoxModel();
while (rs.next()) {
m.addElement(rs.getObject(1).toString());
}
jComboBox2.setModel(m);
}
this is within the Add button
String ID = (String) jComboBox1.getSelectedItem();
String mail=Login.user_mail;
try {
dbm.insert(" insert into CourseStudent (StudentEmail, CourseCode ) values ('"+mail+"', '"+ID+"') ");
jComboBox2.addItem(jComboBox1.getSelectedItem());
jComboBox1.removeItem(jComboBox1.getSelectedItem());
} catch (Exception ex)
{
JOptionPane.showMessageDialog(null, "Insertion Faild\n"+ex);
}
and this is with the drop button
try {
String ID = (String) jComboBox2.getSelectedItem();
String mail=Login.user_mail;
dbm.delete("delete from CourseStudent where CourseCode='"+ID+"' And StudentEmail='"+mail+"'");
jComboBox1.addItem(jComboBox2.getSelectedItem());
jComboBox2.removeItem(jComboBox2.getSelectedItem());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Delete Faild\n"+e);
}
i think the problem lays in the combobox1 SQl statement but i really can't see any other way to do it as i need to retrieve the courses from a table while making sure that the user doesn't take it already from another table...
any help would be greatly appreciated as i said i have been using java for a couple of weeks now and i haven't used sql before so i am a little lost

Categories

Resources