Currently Having my fields like that:
final JTextField PID = new JTextField("Product ID", 7);
frame.getContentPane().add(PID);
My method:
public StockItem(Long id, String name, String desc, double price) {
this.id = id;
this.name = name;
this.description = desc;
this.price = price;
}
Trying to use this method with values from my JTextFields, but it does not allow to use JTextFields under my Long/String/double places.
Is there any way how I could convert my JTextFields into the required things without editing my Method.
You should use the text field text and parse it.
long l = Long.parseLong(PID.getText());
double d = Double.parseDouble(PID.getText());
Yes, you can use PID.getText() to get the text, and then you can convert it to whatever you want, like this:
try{
long id = Long.parseLong(PID.getText());
String name = PNAME.getText();
String description = PDESC.getText();
double price = Double.parseDouble(PPRICE.getText());
}catch(Exception e){}
I have used the try-catch block because if the user enters something else instead of long in the PID, then it will catch the exception.
Related
This is how the GUI looks
I have a GUI program that stores user's details (such as salary, fname, lname, date) into an arraylist using an add button. After the user presses add, the user presses list to output all the information into a panel.
My full code is below.
public class EmploymentRecords extends javax.swing.JFrame {
ArrayList <Data> Output = new ArrayList <Data>();
Add button:
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
Data d;
String id, firstName, lastName, salary, startDate;
id = txtID.getText();
firstName = txtFName.getText();
lastName = txtLName.getText();
salary = txtSalary.getText();
startDate = txtDate.getText();
d = new Data(id, firstName, lastName, salary, startDate);
Output.add(d);
}
List Button:
private void btnListActionPerformed(java.awt.event.ActionEvent evt) {
String print = "";
for (int i=0; i<=Output.size()-1; i++)
{
print = print + "ID #:" + Output.get(i).id + ", "
+ Output.get(i).firstName + " "
+ Output.get(i).lastName + ", "
+ "$" + Output.get(i).salary + ", "
+ Output.get(i).startDate + "\n ";
}
pnlOutput.setText(print);
}
Remove Button:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
boolean idCheck = Output.contains(id);
if (idCheck == true){
index = Output.indexOf(id);
Output.remove(index);
}
else {
lblError.setText("Employee not found. Please try again.");
}
Data Class:
class Data {
String id, firstName, lastName, salary, startDate;
Data (String _id, String _firstName, String _lastName, String _salary, String _startDate) {
id = _id;
firstName = _firstName;
lastName = _lastName;
salary = _salary;
startDate = _startDate;
}
}
I have everything working such as the list and add button, but my problem is with the Remove button: The user has a button to remove a single employees data from the arraylist based on only writing the the ID in the text area, which also removes all the information outputted to the user in the panel. My code above for the remove button doesnt work and when I press remove, nothing happens and the data stays there in the output panel.
Id really appreciate any help I get on this remove button
This solution uses the streaming API:
private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {
int index;
String id = txtID.getText();
List<Data> elementsWithId = Output.stream() // Use the streaming API on Output
.filter(data -> data.id.equals(id)) // filter out the element(s) with matching id
.collect(Collectors.toList()); // put the findings into a new list
boolean idCheck = (elementsWithId.size() > 0);
if (idCheck == true){
for (Data data: elementsWithId) {
Output.remove(data);
}
}
else {
lblError.setText("Employee not found. Please try again.");
}
// Pass the event on to the list functionality:
btnListActionPerformed(evt);
}
So, the real "magic" happens in the commented lines. You'll search the whole Output list for elements with the given ID and create a new list containing the matches only. (I understood, there should be one at most, but you never know...)
The rest is quite the same as you had it before, just that we're working with the result list here.
Please note, that there are serveral approaches to your problem and this is just one the quick and easy ones. There are more elaborate ones for sure.
I am doing a school management system project, everything is good except when I try to click the save button it returns the JOption error message that phone must be integer although it is already. I must say I have a similar form for teacher registration and that one works. How can it be?
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
int day = Integer.valueOf((String)jComboBoxDay.getSelectedItem());
int month = Integer.valueOf((String)jComboBoxMonth.getSelectedItem());
int year = Integer.valueOf((String)jComboBoxYear.getSelectedItem());
String birthDate = ""+day+month+year;
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
String address = jTextFieldAddress.getText();
String email = jTextFieldEmail.getText();
int phoneNumber = Integer.parseInt((jTextFieldPhoneNumber).getText());
String gender = (String)jComboBoxGender.getSelectedItem();
String religion = jTextFieldReligion.getText();
String contactTeacher =jTextFieldContactTeacher.getText();
int contactPhoneNumber = Integer.parseInt((jTextFieldContactPhoneNumber).getText());
int momID = Integer.parseInt((jTextFieldMotherID).getText());
int fatherID = Integer.parseInt((jTextFieldFatherID).getText());
Reset();
Students student = new Students(birthDate,firstName,lastName,address, email,phoneNumber,gender,religion,contactTeacher,contactPhoneNumber,momID,fatherID);
studentsControl.createStudents(student);
loadTable();
}
catch (NumberFormatException exception)
{
JOptionPane.showMessageDialog(null,"Phone must be an integer ","Error",JOptionPane.ERROR_MESSAGE);
jTextFieldPhoneNumber.setText("");
}
}
You're getting the month description from jComboBoxMonth object.
Try getting the index instead by calling getSelectedItem method and adding 1.
I need to convert Strings of this format into an Array of objects.
[{name=Nancy Chapman, email=nchapman0#comcast.net}, {name=Jimmy Fisher, email=jfisher1#photobucket.com}]
Is there any easy way to convert this without having to do it completely manually?
UPDATE:
I am pulling these values from a custom SQL database (Amazon Athena). And the custom JDBC does not support getArray() so it looks like I need to manually parse the columns that contain an Array of Structs. It is unfortunately a limitation of the DB and I have no control over it. This is the format the SQL database returns when I call getString() on the column.
SQL Table Definition
id (int)
threadid (int)
senderemail (string)
sendername (string)
subject (string)
body (string)
recipients (array<struct<name:string,email:string>>)
ccrecipients (array<struct<name:string,email:string>>)
bccrecipients (array<struct<name:string,email:string>>)
attachments (array<binary>)
date (timestamp)
Java Objects
MessageObj
public class MessageObj {
private int id;
private int threadId;
private String senderEmail;
private String senderName;
private String subject;
private String body;
private List<RecipientObj> recipients;
private List<RecipientObj> ccRecipients;
private List<RecipientObj> bccRecipients;
private List<File> attachments;
private Calendar date;
}
RecipientObj
public class RecipientObj {
private String email;
private String name;
}
Parsing the data.
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
// Retrieve table column.
int id = rs.getInt("id");
Integer threadId = rs.getInt("threadid");
String senderEmail = rs.getString("senderemail");
String senderName = rs.getString("sendername");
String subject = rs.getString("subject");
String body = rs.getString("body");
//How to convert recipients into ArrayList? rs.getArray("recipients") not supported.
//... Code here to add into an ArrayList of MessageObj.
}
Perhaps I'm misunderstanding your question but what you typed should work if you clean it up a bit so that it looks like this:
[{ name:"Nany Chapman", email:"nchapman0#comcast.net"},
{ name:"Nany Chapman", email:"nchapman0#comcast.net"}]
Rather than use the equal sign, use a colon and put quotation marks around your values.
How to a write a single generalized for these? I mean the function should take parameters and return the desired string.
String fullName = driver.findElement(By.className("full-name")).getText();
String title = driver.findElement(By.className("title")).getText();
String locality = driver.findElement(By.className("locality")).getText();
String industry = driver.findElement(By.className("industry")).getText();
String connections = driver.findElement(By.xpath("//div[#class='member-connections']/strong")).getText();
String profileLink = driver.findElement(By.className("view-public-profile")).getText();
The function should be something like this:
String getInfo(String className, String byType) {
return driver.findElement(By.byType(className)).getText();
}
EDIT:
I have written this function, but I am not sure how to append byType with By.
static String getInfo(WebDriver driver, String byType, String byParam) {
return driver.findElement(By. + byType + (byParam)).getText();
}
Thanks!
This seems way easier than others are answering so I'm going to put my neck on the line. and say, what's wrong with this...
public String get(WebDriver driver, By by) {
return driver.findElement(by).getText();
}
..and using it like...
String a = get(urDriver, By.className(someName));
String b = get(urDriver, By.xpath(somePath));
You may try this:
public String byXpath(String xpath) {
return driver.findElement(By.xpath(xpath)).getText();
}
public String byClass(String $class) {
return driver.findElement(By.className($class)).getText();
}
Edited:
public String by(By by) {
return driver.findElement(by).getText();
}
String x = by(By.className(name));
String y = by(By.xpath(path));
I am new to hibernate and am having difficulty trying to get it to work for anything other than a direct table mapping scenario. Basically, I have a user defined Java class called: BookInvoice. This class is a non-persistent (not a db table) and uses columns from previously defined and Annotated) db tables. Every time I try to label it as an #Entity it tells me I cant because it is not an existing db table. How do I map it so that I dont get the
Unknown entity: com.acentia.training.project15.model.BookInvoice
error message that I have been experiencing.
My sql queries are good and I am able to get the info from the db; however, they come back as class Object and I am not permitted to cast them into my desired BookInvoice class in order to send it back to the calling method. Below pls find snipets of my work thus far . . .
Please note all of my regular classes that conform to existing db tables queries work fine, it is just the ones that are non-persistent that I am having issues with.
PurchaseOrderInvoiceDAO:
List<BookInvoice> bInvoiceList = null;
final String bookInvoiceQuery =
"SELECT Books.ID, PO_Details.QUANTITY, Books.ISBN, Books.TITLE, Books.AUTHOR, Author.Name, Books.PUBLISHED, Books.COVER, Books.SERIES, Books.SERIES_NO,\n" +
" Books.SUBJECT_ID,Books.PRICE\n" +
" FROM Purchase_Order, PO_Details, Books, Author\n" +
" WHERE Purchase_Order.ID=?\n" +
" AND Purchase_Order.ID=PO_Details.PO_ID\n" +
" AND PO_Details.Book_ID=Books.ID\n" +
" AND Books.AUTHOR=Author.ID";
Query bookInvoicQ = getSession().createSQLQuery(bookInfoQuery).addEntity(BookInvoice.class);
bookInvoicQ.setInteger(0, id);
bList = (List<Books>) bookInvoicQ.list();
BookInvoice class:
public class BookInvoice {
Integer id = null;
Integer quantity = null;
String isbn = null;
String title = null;
Integer authorId = null;
Date publishedDate = null;
String cover = null;
String series = null;
Integer seriesNo = null;
Integer subjectId = null;
Double price = null;
public BookInvoice(final Integer id, final Integer quantity, final String isbn, final String title,
final Integer authorId, final Date publishedDate, final String cover,
final String series, final Integer seriesNo, final Integer subjectId, final Double price) {
this.id = id;
this.quantity = quantity;
this.isbn = isbn;
this.title = title;
this.authorId = authorId;
this.publishedDate = publishedDate;
this.cover = cover;
this.series = series;
this.seriesNo = seriesNo;
this.subjectId = subjectId;
this.price = price;
}
public BookInvoice(){}
public Integer getId() {
return id;
}
etc. . . .
Stack Trace Snippet:
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
Unknown entity: com.acentia.training.project15.model.BookInvoice
File: org/hibernate/impl/SessionFactoryImpl.java
Line number: 693
Stacktraces
org.hibernate.MappingException: Unknown entity:
com.acentia.training.project15.model.BookInvoice
org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:693)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.getSQLLoadable(SQLQueryReturnProcessor.java:335)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processRootReturn(SQLQueryReturnProcessor.java:376)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.processReturn(SQLQueryReturnProcessor.java:355)
org.hibernate.loader.custom.sql.SQLQueryReturnProcessor.process(SQLQueryReturnProcessor.java:171)
org.hibernate.loader.custom.sql.SQLCustomQuery.(SQLCustomQuery.java:87)
org.hibernate.engine.query.NativeSQLQueryPlan.(NativeSQLQueryPlan.java:67)
org.hibernate.engine.query.QueryPlanCache.getNativeSQLQueryPlan(QueryPlanCache.java:166)
org.hibernate.impl.AbstractSessionImpl.getNativeSQLQueryPlan(AbstractSessionImpl.java:160)
org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:157)
com.acentia.training.project15.bo.PurchaseOrderInvoiceBO$PurchaseOrderInvoiceDAO.getById(PurchaseOrderInvoiceBO.java:196)
...
Ok! Finally broke down and talked to my supervisor about this. He explained that I am doing like waaaaaay to much extra work on this.
Basically, if I set the #Entity class/DB mappings up correctly then they will get all of the right information (ie. #OneToMany, etc.) from the mappings of the classes that correspond directly to the DB tables. Basically, Hibernate will go down as many levels (PO_Details ->Payments->Books, etc) they would give me all the additional information that I need and I wouldn't need to create my own custom classes.