How can I print a void method inside a button using Swing? - java

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()));
}
}
}

Related

How do I store values from a database into a collection?

public String getDataOfpersons() {
try {
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while(rs.next()) {
String name = rs.getString("name");
String age = rs.getString("age");
System.out.println("Name: " + name + " " + "age: " + age);
}
}catch(Exception ex) {
System.out.println(ex);
}
return null;
}
So I have this part of code and I am reading it from mysql database and I am wondering how could I store object to collection (Name and age) ?
First, create a Person class with "name" and "age" fields. Also add the corresponding getters and setters.
Then modify modify your code like this:
// change the return type
public List<Person> getDataOfpersons() {
// create a list to store values
List<Person> personList = new ArrayList<>();
try {
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while (rs.next()) {
Person person = new Person();
String name = rs.getString("name");
String age = rs.getString("age");
person.setName(name);
person.setAge(age);
personList.add(person);
System.out.println("Name: " + name + " " + "age: " + age);
}
} catch(Exception ex) {
System.out.println(ex);
}
return personList;
}
Don't know if this is what u looking for without changing the existing signature of the method
public String getDataOfpersons() {
try {
Map<String,String> map = new HashMap<>();
String query = "select * from persons";
rs = st.executeQuery(query);
System.out.println("Records from persons database");
while(rs.next()) {
String name = rs.getString("name");
String age = rs.getString("age");
//System.out.println("Name: " + name + " " + "age: " + age);
map.put("Name",name);
map.put("age",age);
System.out.println(map);
}
}catch(Exception ex) {
System.out.println(ex);
}
return null;
}

Why the place of the option always change?

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.

How to implement Interface Comparable, Collection.sort() using SQL in java?

That is simple Library project. It has to load the data from the database, by asking the user to search based on keywords or genres.
I have two classes. One of them is the Book class. :
package library;
import java.sql.Date;
public class Book implements Comparable<Book> {
String title;
String author;
Date date;
String ISBN;
String format;
String publisher;
float price;
String[] keywords;
String[] inputArray;
String input;
public Book(String title_param, String author_param, java.util.Date date_param, String ISBN_param,
String format_param, String publisher_param, float price_param, String keywords_param) {
title = title_param;
author = author_param;
date = (Date) date_param;
ISBN = ISBN_param;
format = format_param;
publisher = publisher_param;
price = price_param;
keywords = keywords_param.split(",");
}
public void setUserInput(String userIn) {
input = userIn;
}
private int getRelevance(String userInput) {
inputArray = userInput.split(",");
int num = 0;
for (int i = 0; i != keywords.length; i++) {
String in = inputArray[i];
for (int l = 0; l != keywords.length; l++) {
if (in.equals(keywords[l]))
num++;
}
}
return num;
}
public int compareTo(Book o) {
if (this.getRelevance(input) > o.getRelevance(input)) {
return 1;
} else if (this.getRelevance(input) < o.getRelevance(input)) {
return -1;
}
return 0;
}
}
In the second one I want to CALL in the right way Collection.sort() and CompareTo(), in a way that it shows the books that contain at least one of these keywords. BUT it has to show the books on top that have the most keywords from the input.
The collection and the compare parts
are NOT not working right now.
package library;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Scanner;
public class LibrarySearch {
static ArrayList<Book> books = new ArrayList<Book>();
ArrayList<LibrarySearch> genres = new ArrayList<LibrarySearch>();
static ArrayList<LibrarySearch> keywords = new ArrayList<LibrarySearch>();
public static void main(String[] args) {
load_data();
}
private static void load_data() {
Collections.sort(books, new Comparator<Book>() {
#Override
public int compare(Book first, Book second) {
if (first.compareTo(second) == 1) {
return 1;
} else if (first.compareTo(second) == -1) {
return -1;
}
return 0;
}
});
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/library", "root", "123456");
statement = connection.createStatement();
System.out.println("Choose to search by keywords or genres");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
if (input.equals("keywords")) {
System.out.println("Enter your keywords: ");
String[] keyWordsInput = scanner.nextLine().split(",");
ResultSet result = null;
for (int i = 0; i != keyWordsInput.length; i++) {
result = statement
.executeQuery(" SELECT * FROM book WHERE keywords LIKE '%" + keyWordsInput[i] + "%'");
}
while (result.next()) {
int id = result.getInt("id");
String title = result.getString("title");
String author = result.getString("author");
Date date = result.getDate("date");
String ISBN = result.getString("ISBN");
String format = result.getString("format");
String publisher = result.getString("publisher");
float price = result.getFloat("price");
String keywords = result.getString("keywords");
System.out.println("ID = " + id);
System.out.println("TITLE = " + title);
System.out.println("AUTHOR = " + author);
System.out.println("DATE = " + date);
System.out.println("ISBN = " + ISBN);
System.out.println("FORMAT = " + format);
System.out.println("PUBLISHER = " + publisher);
System.out.println("PRICE = " + price);
System.out.println("KEYWORDS = " + keywords);
System.out.println("___________________________________________________________________________");
if (title.equals("I,Robot")) {
Book new_book = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book);
}
if (title.equals("Catch-22")) {
Book new_book1 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book1);
}
if (title.equals("Pride and Prejudice")) {
Book new_book2 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book2);
}
if (title.equals("Gone with the Wind")) {
Book new_book3 = new Book(title, author, date, ISBN, format, publisher, price, keywords);
books.add(new_book3);
}
}
result.close();
statement.close();
connection.close();
} else if (input.equals("genres")) {
System.out.println("Enter your genres" + ": ");
String genresInput = scanner.nextLine();
ResultSet result = statement.executeQuery(
" SELECT * FROM books_genres JOIN book ON (book.id = books_genres.book_id) JOIN genre ON (genre.id = books_genres.genre_id) WHERE name LIKE '%"
+ genresInput + "%' ");
while (result.next()) {
int id = result.getInt("id");
String name = result.getString("name");
int book_id = result.getInt("book_id");
int genre_id = result.getInt("genre_id");
int id1 = result.getInt("id");
String title = result.getString("title");
String author = result.getString("author");
Date date = result.getDate("date");
String ISBN = result.getString("ISBN");
String format = result.getString("format");
String publisher = result.getString("publisher");
float price = result.getFloat("price");
String keywords = result.getString("keywords");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Book ID = " + id1);
System.out.println("TITLE = " + title);
System.out.println("AUTHOR = " + author);
System.out.println("DATE = " + date);
System.out.println("ISBN = " + ISBN);
System.out.println("FORMAT = " + format);
System.out.println("PUBLISHER = " + publisher);
System.out.println("PRICE = " + price);
System.out.println("KEYWORDS = " + keywords);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Genre ID = " + id);
System.out.println("Genre Name = " + name);
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("Book ID = " + book_id);
System.out.println("Genre ID = " + genre_id);
}
result.close();
statement.close();
connection.close();
}
else {
System.out.println("Sorry, wrong command");
}
} catch (SQLException ex) {
System.out.println("No successful connection");
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
}
catch (ClassNotFoundException x_not_found) {
System.out.println("Class not found");
}
}
}
First off, since getRelevance() method returns int, I would suggest writing compareTo like this:
public int compareTo(Book o) {
return this.getRelevance(input) - o.getRelevance(input);
}
Similarly, comparator would look like this:
Collections.sort(books, new Comparator<Book>() {
#Override
public int compare(Book first, Book second) {
return first.compareTo(second);
}
});
As for calling, looks like you are sorting the empty list first, and then populate it with search results. I suggest moving the sorting part to the end of the load_data() method.
One problem: You're iterating over inputArray keywords.length times, which is probably not correct. Don't know if that's your problem - it might be if the keywords array is much shorter than the input array.
The larger issue is iterating over keywords for ever element of inputArray. Put your keywords in a HashSet and test for contains instead.

Before start of result set running multiple sql

I'm currently working on an application for a restaurant. The idea for the code I'm currently working on is that it gets the name from a combobox and inserts a receipt into the database whith the employee number of the person who is working on it. The code whith which I'm trying to do it is:
RestaurantOrder sqlRestaurantOrder = new RestaurantOrder();
ActionListener printReceiptListner;
printReceiptListner = (ActionEvent) -> {
int ID = Integer.parseInt(input1.getText());
try {
SystemManager manager = new SystemManager();
ResultSet rs = manager.stmt.executeQuery(sqlRestaurantOrder.setIdSql(ID));
while (rs.next()) {
double totalPrice = rs.getDouble("sumprice");
if (ID > 0) {
Receipt receiptSql = new Receipt();
String firstName = (String) cb.getSelectedItem();
String checkoutDate = new SimpleDateFormat("yyyyMMdd").format(Calendar.getInstance().getTime());
ResultSet rs2 = manager.stmt.executeQuery(receiptSql.getEmployeeId(firstName));
int employeeId = rs2.getInt("id");
while (rs2.next()) {
Receipt receiptSql2 = new Receipt();
ResultSet rs3 = manager.stmt.executeQuery(receiptSql2.SetStatusReceipt(employeeId, checkoutDate, ID, totalPrice));
while (rs3.next()) {
}
}
}
}
} catch (SQLException k) {
JOptionPane.showMessageDialog(null, k.getMessage());
}
};
The statements are:
public class Receipt {
public String sql;
public String sql2;
public String getEmployeeId(String firstName){
return sql2 = "SELECT id FROM employee WHERE firstName = '" + firstName + "';";
}
public String SetStatusReceipt(int employeeId, String checkoutDate, int id, double totalPrice){
return sql = "INSERT INTO `receipt` (`employeeId`, `price`, `restaurantOrderId`, `checkoutDate`) VALUES (" + employeeId + " , " + totalPrice + ", " + id + ", " + checkoutDate + ");";
};
}
I'm getting the error before start of result set which I looked up what it means but I can't get it fixed at the moment. Help will be appreciated.
If I forgot to post more important code let me know I'll update it
You have to call ResultSet.next() before you are able to access the fields of that ResultSet. So you need to move your assignment of employeeId into your while loop:
while (rs2.next()) {
int employeeId = rs2.getInt("id");
From the documentation of ResultSet.next():
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

problem w/ multiple jcombobox

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.

Categories