I've been working with a project that requires me to use mutiple jcombobox. I did try to chain three jcombobox but failed to show all necessary drop-down lists.
In one of my combobox I have lists of Banks (Bank1, Bank2), the other one is the list of all branches in a specific Bank that has been selected (Bank1(branch1-1, branch1-2), Bank2(branch2-1, branch2-2)) and the last one are the account # for all specific branches that has been selected. Each branches has a multiple accounts.
I have no problem working with 2 comboboxes, all branches are shown for a specific Bank that has been selected, but, when I added the third combobox which is the account #, only one branch is being queried from my db. ex. if I select Bank1 only "branch1" will be on the list, and if Bank2 only branch2-1 will be on the list also, but account # for that specific branches are on the drop-down lists.
private void populateSavingsAccountComboBox() {
accountNo.removeAllItems();
bankBranch.removeAllItems();
selectBank();
bankName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String bank = bankName.getSelectedItem() == null ?
"" : bankName.getSelectedItem().toString();
selectBranch(bank);
}
});
bankBranch.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
Object source = e.getSource();
JComboBox target = (JComboBox) e.getSource();
String branch = target.getSelectedItem() == null ?
"" : target.getSelectedItem().toString();
if (e.getStateChange() == ItemEvent.SELECTED) {
selectAccountNo(bankName.getSelectedItem().toString(), branch);
}
}
});
}
private void selectBank() {
List bankList = new ArrayList();
try {
stmt = conn.createStatement();
rs = stmt.executeQuery(" SELECT bankName FROM bank_tbl ");
bankName.removeAllItems();
while (rs.next()) {
String bank = rs.getString("bankName");
bankList.add(bank);
Object bankElement = bankList.get(bankList.size() - 1);
bankName.addItem(bankElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
}
private String selectBranch(String bank) {
try {
List branchList = new ArrayList();
rs = stmt.executeQuery(" SELECT branch FROM bank_branch_tbl WHERE "
+ " bankName = '" + bank + "' ");
bankBranch.removeAllItems();
while (rs.next()) {
branchList.add(rs.getString("branch"));
Object branchElement = branchList.get(branchList.size() - 1);
bankBranch.addItem(branchElement);
}
} catch (SQLException ex) {
Logger.getLogger(addContact.class.getName()).log(Level.SEVERE, null, ex);
}
return bank;
}
private String selectAccountNo(String bank, String branch) {
List accountNoList = new ArrayList();
try {
rs = stmt.executeQuery(" SELECT accountNo FROM account_no_tbl WHERE "
+ " bankName = '" + bank + "' AND "
+ " branch = '" + branch + "' ");
accountNo.removeAllItems();
while (rs.next()) {
accountNoList.add(rs.getString("accountNo"));
Object accountNoElement = accountNoList.get(accountNoList.size() - 1);
accountNo.addItem(accountNoElement);
}
} catch (SQLException ex) {
Logger.getLogger(addSavings.class.getName()).log(Level.SEVERE, null, ex);
}
return branch;
}
problem solved. I was using one-single variable for all ResultSet. tsk! thank you for replying to my post.
Related
I'm using JDBC to make a banking system with Java. The user should be able to type in a number in a text field, and deposit said amount of money into the bank account. I would like to then update the account balance in the Microsot Access database.
I currently have this:
try (Connection con = DriverManager.getConnection("jdbc:ucanaccess://C://Users//User//IdeaProjects//Database4.accdb")) {
Statement users = con.createStatement();
ResultSet sr = users.executeQuery("Select * from Registrations");
Boolean duplicate = false;
while (sr.next()) {
if (userID.equals(sr.getString(2))) {
match = sr;
duplicate = true;
System.out.println("Welcome " + match.getString(2));
System.out.println("Your balance is " + match.getString(3));
break;
}
}
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == depositButton) {
String depositString = depositField.getText();
int depositAmount = Integer.parseInt(depositString);
try {
System.out.println(match.getInt(3) + depositAmount);
match.updateInt("AccBalance", match.getInt(3) + depositAmount);
match.updateRow();
}
catch (SQLException ex) {
ex.printStackTrace();
}
When I try to do this, I get the error 'attempt to assign to non-updatable column'.
I'm very new to Java and tried looking online to find fixes for this issue but couldn't find anything useful.
Try the code below
try (Connection con = DriverManager.getConnection("jdbc:ucanaccess://C://Users//mghosh22//IdeaProjects//Database4.accdb")) {
// Query example UPDATE user SET balance = 10000 WHERE user.id = 1;
PreparedStatement updateBalance = conn.prepareStatement("UPDATE <table> SET balance = ? WHERE <wich row update>");
// For each query parameter, set a value to execute the same
// preparedStatement.setParameterType(countEach?StartingWithOne, yourQueryParameter);
updateBalance.setDouble(1, 10,000.00);
// Execute update return the amount of rows your query affected, how we are talking about account balance, the number of rows affected may be ever one
if (updateBalance.executeUpdate() == 1) {
System.out.println("Row updated");
}
}
I have a form that has a ComboBox which it gets its items from a database. The combobox takes numerous column-items from a table inside the database.
I want to take only one of these items (from the combobox) and copy it to a JTextField.
Here's the code of the creation of the ComboBox in the Order.java file:
cbinv = new JComboBox<>();
cbinv.setModel(new InvComboModel(con));
and the code from the InvComboModel.java:
public InvComboModel(Connection con) {
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM inventory";
rs = stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println("InvComboModel: " + e.getMessage());
}
}
#Override
public String getElementAt(int index) {
String lstn = null;
try {
rs.absolute(index + 1);
lstn = rs.getString("category") + ", " + rs.getString("description") + ", "
+ rs.getInt("price") + ", " + rs.getInt("quantity");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return lstn;
}
#Override
public int getSize() {
int cnt = 0;
try {
rs.last();
cnt = rs.getRow();
} catch (SQLException ex) {
System.out.println("getSize(): " + ex.getMessage());
}
return cnt;
}
public int getIdInvAt(int index) {
int idInv = 0;
try {
rs.absolute(index + 1);
idInv = rs.getInt("idinv");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return idInv;
}
So, I want when I select something on the Inventory Item to take the third value (which in this case is 500, example image) and copy it to the JTextField of the ItemPrice.
[example][1]: https://i.stack.imgur.com/BWQVw.jpg
In the Order.java file I have the following command but it copies all the selected item in the combobox:
tip.setText((String) cbinv.getSelectedItem());
and when I use the following command it takes the whole line again. It seems that I can't use any other method from the InvComboModel.java file
tip.setText((String) cbinv.getModel().getElementAt());
Thanks in advance.
i am pretty new i am sorry if i use terms incorrect. I am trying to learn Swing and import it to my current project. In my main file, a method prints a list from mysql database. I want this : when button pressed, print this output to textfield or dialog window, show on the gui, not only cmd output. I hope I could explain my request correctly. I use Netbeans as IDE.
method in Baglanti.java :
public void dogList() {
String sorg = "Select * From dogs";
NewJFrame frame1 = new NewJFrame();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and my list button in NewJFrame.java
private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
Baglanti baglanti = new Baglanti();
// i don't know what next
Thanks.
So first, let's fix your doglist() method. I have Given it a PrintStream parameter so that it can be used with System.out but also with any other PrintStream. I have also taken out the "NewJFrame" creation. This shouldn't go there.
public void dogList(PrintStream stream) {
String sorg = "Select * From dogs";
//Take this out
//NewJFrame frame1 = new NewJFrame();
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
stream.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Now, all you need is a PrintStream for a JTextField or a Dialog. And the easiest way to get this is to use a ByteArrayOutputStream and then convert that to a String and set it in the JComponent
ByteArrayOutputStream bstream = new ByteArrayOutputStream();
PrintStream myPS = new PrintStream(bstream);
dogList(myPS);
String msg = new String(bstream.getBytes());
Now you can use JTextField.setText(msg), or do something similar within your JFrame/Dialog.
It seems you do not need to create another instance of NewJFrame in dogList method of Baglanti class.
Also, it may be redundant to create an instance of Baglanti class in NewJFrame each time when you press on the button. It would suffice to have a single instance of this class responsible for retrieval of the data from the DB.
Next, you need to refactor the code of dogList method so that it begins to return a list of relevant data classes (e.g. Dog) to the caller. Then you'll be able to use this list in the frame and show its data as needed: in a text area, table, list, etc.
That being said, some code snippets:
// data transfer class Dog
public class Dog {
private int id;
private String name;
private String species;
private int age;
private String owner;
private String date;
// constructor with all args, getters/setters
}
import java.util.*;
public class Baglanti {
// ...
public List<Dog> dogList() {
String sorg = "Select * From dogs";
List<Dog> result = new ArrayList<>();
try (statement = con.createStatement()) { // use try-with-resources to make sure the statement is closed
ResultSet rs = statement.executeQuery(sorg);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String species = rs.getString("species");
int age = rs.getInt("age");
String owner = rs.getString("owner");
String date = rs.getString("date");
System.out.println(" id : " + id + " name: " + name+ " species: " + species+ " age: " + age+ " owner: " + owner+ " date: " + date);
// assuming all-args constructor is implemented in Dog
Dog dog = new Dog(id, name, species, age, owner, date);
result.add(dog);
}
} catch (SQLException ex) {
Logger.getLogger(Baglanti.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
// ... other methods
}
Remaining part in NewJFrame:
public class NewJFrame extends JFrame {
Baglanti baglanti = new Baglanti();
//... other UI components
private void listbuttonActionPerformed(java.awt.event.ActionEvent evt) {
List<Dog> dogs = baglanti.dogList();
for (Dog dog : dogs) {
// set information about the dog in other UI components
textArea.append(String.format("Dog id=%d named: %s, age %d years, owner: %s",
dog.getId(), dog.getName(), dog.getAge(), dog.getOwner()));
}
}
}
I'm doing a phone book project in Java, using MySql for school.
I wanted to print the methods using the Class.getDeclaredMethods();
adding them to a Vector of type String.
and invoke a menu() method that prints and accepts the option from the user using Scanner
the problem is that it always changes the methods places.
for example it can print
0.addPerson
1.deleteContact
2.searchByChar
and the next time
0.deleteContact
1.addPerson
2.searchByChar.
the problem is that i have a Switch case depend on it.
the menu function:
public static int menu(Vector<?> options){
System.out.println("The Options: ");
for (int i = 0; i < options.size(); i++) {
System.out.println(i + ". " + options.get(i));
}
Scanner scanner = new Scanner(System.in);
System.out.println("Your Choice: ");
String optionString = scanner.nextLine();
int option = 0;
if(isNumber(optionString)){
option = Integer.valueOf(optionString);
}else{
System.out.println("Please Choose Valid Option");
return menu(options);
}
return option;
}
the methods that get my methods:
public static Vector<String> getClassMethods(Class whichClass){
Method[] methods = whichClass.getDeclaredMethods();
Vector<String> stringMethods = new Vector<>();
for (Method method : methods) {
if(Modifier.toString(method.getModifiers()).equals("protected")){
stringMethods.add(method.getName());
}
}
return stringMethods;
}
my class the connects to the data base:
private boolean getData(Person person){
String sql = "SELECT * FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
if (resultSet.next()) {
return true;
}
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return false;
}
protected void addPerson(){
Person person = MyUtills.createPerson();
if(getData(person)){
System.out.println(person.getName() + ", " + person.getPhoneNumber() + ": Already in Contacts" );
}else{
add(person);
}
}
private void add(Person person) {
String pName = person.getName();
String pPhone = person.getPhoneNumber();
String pAddress = person.getAddress();
String sql = "INSERT INTO " + DB_NAME + " (name,phone_number,address)" +
"VALUES (?,?,?)";
try {
statement = db.prepareStatement(sql);
statement.setString(1,pName);
statement.setString(2,pPhone);
statement.setString(3,pAddress);
statement.execute();
System.out.println("Added Successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
//delete contact by name
protected void deleteContact(){
System.out.println("Enter Name Please");
String name = MyUtills.readStringFromUser();
Vector<Person> vector = checkMoreThanOne(name);
if(vector.size() > 1){
System.out.println("Choose One To Delete: ");
int option = menu(vector);
delete(vector.get(option));
}
System.out.println("Deleted");
}
private Vector<Person> checkMoreThanOne(String name) {
Vector<Person> vector = new Vector<>();
String sql = "SELECT * FROM " + DB_NAME;
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
while(resultSet.next()){
String pName = resultSet.getString("name");
String pPhone = resultSet.getString("phone_number");
String pAddress = resultSet.getString("address");
if(pName.equals(name)){
vector.add(new Person(pName,pPhone,pAddress));
}
}
return vector;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//deleting and existing contact;
private void delete(Person person){
String sql = "DELETE FROM " + DB_NAME + " WHERE name = '" + person.getName() + "' and phone_number = '" + person.getPhoneNumber() + "'";
try {
statement = db.prepareStatement(sql);
statement.execute();
System.out.println("Deleted Successfully");
} catch (SQLException e) {
e.printStackTrace();
}
}
//creating a new table for empty data base!
private void createTable() {
try {
statement = db.prepareStatement(SQL_TABLE_STRING);
statement.execute();
} catch (SQLException e) {
e.printStackTrace();
}
}
protected void searchByFirstChar(Character character){
Vector<Person> personVector = new Vector<>();
String sql = "SELECT * FROM newphonebook";
try {
ResultSet resultSet = db.prepareStatement(sql).executeQuery();
while(resultSet.next()){
String name = resultSet.getString("name");
String phoneNum = resultSet.getString("phone_number");
String address = resultSet.getString("address");
if(character.equals(name.charAt(0))){
personVector.add(new Person(name,phoneNum,address));
}
}
System.out.println(personVector);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
public void getOptions(){
Vector<String> options = MyUtills.getClassMethods(DBWriterReader.class);
int option = MyUtills.menu(options);
switch (option){
case 0:
addPerson();
break;
case 1:
deleteContact();
break;
case 2:
// searchByFirstChar();
break;
}
}
}
I know it's not best written but I'm working on it to make it better
The Writing and Reading from the data base works fine, its the way it prints my methods that makes the problem..
If you need to guarantee the order of elements in a data structure, you don't use Vector -- it's not 1999 anymore. Look at the documentation for Vector. You get elements in the order determined by an iterator, not as they are stored.
Change your data structure to an ArrayList, which guarantees order. ArrayLists are also more performant in a single threaded application like yours, because unlike Vector, an ArrayList skips the overhead associated with being synchronized. Using the index of the ArrayList elements may also simplify the way you construct your switch statement.
I have already used the fireDataChanged methods but I think due to the fact that this is connected to my database it will not do anything.
DelBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selRow = table.getSelectedRow();
Object element = table.getValueAt(selRow, 0);
th = table.getTableHeader();
tcm = th.getColumnModel();
Statement statement = null;
try {
statement = ResultSetTableModelFactory.connection
.createStatement();
if (JisSelected == true) {
String delete = "DELETE FROM J WHERE JNO = '" + element + "';";
statement.executeUpdate(delete);
}
if (SPJisSelected == true) {
String delete = "DELETE FROM SPJ WHERE SNO = '" + element + "';";
statement.executeUpdate(delete);
}
System.out.println(element);
} catch (Exception ex) {
//ex.printStackTrace();
}
model.fireTableDataChanged();
}
});
}
Your ActionListener should perform its work in your implementation of the doInBbackground() method of a SwingWorker. In the interim, you should signify that the operation is pending in whatever way is appropriate to your application, perhaps in a renderer or status indicator. If the database operation succeeds, update the TableModel in your implementation of done(). In no case should you invoke fireTableDataChanged() except from within the model.