access JComponents into another java non GUI class - java

How can I access any JComponent (e.i. JTextField) of a class in another non GUI class? I want to access them so that I can implement all my functions in a non GUI class and then call those functions in the GUI listener.
For example:
public class New_Client {
private JFrame frmNewClient;
private JTextField txt_FirstName,txt_LastName,txt_Address,txt_Phone;
private JButton submit;
public New_Client() {
//initializing frame and other components
...
txt_FirstName = new JTextField();
txt_FirstName.setBounds(350,220,300,80);
frmNewClient.getContentPane().add(txt_FirstName);
submit = new JButton("Submit");
submit.setSize(115,55);
submit.setLocation(800,420);
frmNewClient.getContentPane().add(submit);
submit.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
ReceptionsitClass.insertRecords();
}
});
}
}
And the other class is as follows:
public class Person {
private int id;
private String firstName, lastName, address, phone;
public Person(int ID, String fName, String lName, String addr, String tel){
this.id = ID;
this.firstName = fName;
this.lastName = lName;
this.address = addr;
this.phone = tel;
}
public int getID(){
return this.id;
}
}
And another class is ReceptionistClass which implements the insert function:
public class ReceptionistClass {
public void InsertRecord() {
Connection.getDBConnection().Connect();
//String FirstName = txt_FirstName.getText();
// How can I access txt_FirstName.getText() so that I can pass that value to the query and store it...
...
// Person p = New Person(ID, FirstName,LastName, Adress, Phone);
}
}

There are some issues and some ways to make it right.
Simplest way (not recommended) make field static and public:
public static JTextField txt_FirstName,txt_LastName,txt_Address,txt_Phone;
than you can access it in any class like this
String FirstName = New_Client.txt_FirstName.getText();
A little better way is make it not static but then you have to have instance of this New_Client in your classes and use it like this:
New_Client new_client=null; // initialize it before use
//...
String FirstName = new_client.txt_FirstName.getText();
There are other more appropriate ways to this in right way. I would recommend MVC Model-View-Controller. You should separate your data from your view and controls. Maybe it looks like overkill for simple SWING application but that's the right way to do it.

You're going about this backwards.
When you build a GUI, you should use the model / view / controller pattern. Not only do you separate your concerns into a model, a view, and one or more controllers, you develop in this order. First, you create the model, then the view, and finally the controller(s).
So, let's take a look at your model. I've included all of the getters and the setters.
public class Person {
private int id;
private String firstName, lastName, address, phone;
public Person(int ID, String fName, String lName, String addr,
String tel) {
this.id = ID;
this.firstName = fName;
this.lastName = lName;
this.address = addr;
this.phone = tel;
}
public int getID() {
return this.id;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Next, you have to pass the model to the view. Here's a mostly corrected version of your view.
public class NewClient {
private JFrame frmNewClient;
private JTextField txt_FirstName, txt_LastName, txt_Address, txt_Phone;
private JButton submit;
public NewClient() {
final Person person = new Person(100, "John", "Smith", "", "");
// initializing frame and other components
frmNewClient = new JFrame("New Client");
frmNewClient.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
txt_FirstName = new JTextField();
txt_FirstName.setText(person.getFirstName());
panel.add(txt_FirstName);
submit = new JButton("Submit");
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
person.setFirstName(txt_FirstName.getText().trim());
ReceptionistClass rc = new ReceptionistClass();
rc.insertRecord(person);
}
});
panel.add(submit);
frmNewClient.add(panel);
frmNewClient.pack();
frmNewClient.setVisible(true);
}
}
And finally, you have your controller class writing your Person to the database.
public class ReceptionistClass {
public void insertRecord(Person person) {
Connection.getDBConnection().Connect();
// You don't care about the view here.
// All you care about is the Person instance.
}
}
I hope this helps you to organize your code so that you can focus on one small piece at a time.

Related

How to serialize select class fields to JSON string using the Builder Pattern in Java and Gson?

I created a User class with a Builder Pattern for the purpose of serializing it to a JSON String for POST. Now, the requirements have changed and I need the ability to PATCH an existing record, updating one or more fields but not all fields in a recordset. The example below has 5 fields in its User class but imagine if it had 30 or even 40 fields including the int type.
import com.google.gson.*;
class User
{
//All final attributes
private final String firstName;
private final String lastName;
private final int age;
private final String phone;
private final String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//All getter, and NO setter to provide immutability
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public String getAddress() {
return address;
}
public static class UserBuilder
{
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
public UserBuilder() {
}
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder firstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder lastName(String lastName) {
this.firstName = lastName;
return this;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(String phone) {
this.phone = phone;
return this;
}
public UserBuilder address(String address) {
this.address = address;
return this;
}
//Return the finally consrcuted User object
public User build() {
User user = new User(this);
return user;
}
}
}
public class TestUserBuild {
public static void main(String[] args) {
// TODO Auto-generated method stub
User user = new User.UserBuilder().
//No last name
//No age
//No phone
//no address
.firstName("Super")
.build();
System.out.println(user); // User: Super, null, 0, null, null
Gson gson = new Gson();
System.out.println(gson.toJson(user)); // {"firstName":"Super","age":0}
}
}
I didn't specify the age and, yet, there it is in the JSON string. I thought the builder pattern would facilitate creating any number of JSON string permutations, i.e. update the first name and last name, update the first name only, update the age only, update last name and phone number only, etc...
Is the builder pattern approach not the correct solution for this problem? If it is an acceptable solution, how can I leverage the builder pattern to serialize the User class to a JSON string but with only the fields of my choosing? Is there something I can leverage in the Gson library to realize this task such as creating a custom type adapter? Maybe I can create a custom type adapter that takes all field as inputs, checks if each one is NULL, or 0 for Integers, and then build the JSON string with just the deltas.
Your "age" field is worth 0 because "int" has a default value. Use "Integer" if you want the age field to default to null.
Some of the advantages of the Builder pattern are immutability (you can choose to allow a class to be modified only at creation time by the builder, removing all setters from the class), and that it's more concise for instantiating a class with multiple attributes.
But you don't need to keep your Builder pattern immutable. If I understand your need correctly, you could keep the builder pattern for versatility during object creation, and keep the setters on the class to be able to update fields easily.
import com.google.gson.*;
class User {
//Your attributes don't need to be final
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//getters AND setters (omitted for brevity)
//builder class stays as is, omitted for brevity
public class TestUserBuild {
public static void main(String[] args) {
User user = new User.UserBuilder()
.firstName("Super")
.build();
//when you need to update
user.setAge(42);
}
}
The question is, why do you want immutability if you need to update fields periodically? Should you remove the immutability constraint altogether (by leaving setters in the class)? Do you need to be able to update specific combinations of fields according to particular business rules? If the latter is true, I would recommend moving away from an anemic model (a "bag of getters and setters") and adding domain-specific methods which take care of updating the relevant fields. Your User class would then look like this:
class User {
//Your attributes don't need to be final
private String firstName;
private String lastName;
private int age;
private String phone;
private String address;
private User(UserBuilder builder) {
this.firstName = builder.firstName;
this.lastName = builder.lastName;
this.age = builder.age;
this.phone = builder.phone;
this.address = builder.address;
}
//getters ONLY (omitted for brevity)
//no setters, only domain-relevant methods which update fields as needed
public void setIdentity(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setCoordinates(String phone, String address) {
this.phone = phone;
this.address = address;
}
}
//builder class stays as is
public class TestUserBuild {
public static void main(String[] args) {
User user = new User.UserBuilder()
.firstName("Super")
.build();
//update identity (say, your frontend has an "identity" page with only firstName and lastName on it
user.setIdentity("Chris", "Neve");
//your frontend page allowing user to update coordinates
user.setCoordinates("+331231231", "7th av, NYC");
}
}

Pass a list of string to a declared class file

Hi All below is my Employeeinformation class file java. I have to pass the values to it through java code
I am fine passing the strings but i am unable to pass list of technologies and list of strings.
Technologies.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
#Data
public class Technologies {
private String name;
private String yearsOfExperience;
}
Employeeinformation.java
package com.ElasticSearchCrud.ElasticSearchCrud;
import lombok.Data;
import java.util.List;
#Data
public class EmployeeInformation {
private String id;
private String firstName;
private String lastName;
private List<Technologies> technologies;
private List<String> emails;
public EmployeeInformation(String id, String firstName, String lastName, List<Technologies> technologies, List<String> emails) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.technologies = technologies;
this.emails = emails;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List<Technologies> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technologies> technologies) {
this.technologies = technologies;
}
public List<String> getEmails() {
return emails;
}
public void setEmails(List<String> emails) {
this.emails = emails;
}
}
Passing a value to class file
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali","?","?");
How to pass the list of technologies and list of string in above code. Could some one help me tho achieve this?
List<Technologies> technologies = new ArrayList<>();
technologies.add(new Technologies("name1", "1999"));
technologies.add(new Technologies("name2", "1999"));
List<String> emails = new ArrayList<>();
strs.add("one");
strs.add("two");
EmployeeInformation EmployeePost = new EmployeeInformation("3", "Vignesh", "Murali",technologies,emails);
Also add #AllArgsConstructor to Technologies class. Or use setters to init Technologies objects:
#Data
#AllArgsConstructor
public class Technologies {
private String name;
private String yearsOfExperience;
}
#Data annotation has inner #RequiredArgsConstructor. This constructor is created with all non-initialized FINAL properties.
If you have not final properties there will be empty constructor.
So you have 3 ways:
Set you fields as final: new SomeObject(List.of("1","2"));
Add #AllArgsConstuctor: result the same
Leave as it is and initialize an object by set methods
SomeObject obj = new SomeObject();
obj.setList(List.of("1", "2"));

Adding arraylist object to combobox [duplicate]

This question already has answers here:
How do I populate a JComboBox with an ArrayList?
(8 answers)
Closed 6 years ago.
I've created a JCombobox using Netbeans drag and drop.
I have an ArrayList<Person>.
How do I automatically add the FirstName of the Person into the combobox.
The code generated by Netbeans cant be edited in Source view.
Step 1: Lets say you have the following Person class.
Person.java
public class Person {
private int id;
private String firstName;
private String lastName;
public Person() {
}
public Person(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public String toString() {
return firstName;
}
}
Step 2: Create the instance of JComboBox and set the model.
java.util.List<Person> list=new java.util.ArrayList<Person>();
list.add(new Person(1, "Sanjeev", "Saha"));
list.add(new Person(2, "Ben", "Yap"));
JComboBox<Person> comboBox = new JComboBox<Person>();
comboBox.setModel(new DefaultComboBoxModel<Person>(list.toArray(new Person[0])));
Step 3: Run your program.
public class PersonBox{
List<Person> person= new ArrayList<Person>();
JCombobox box; //=new JCombobox(...) ?
//used to add a new Person to the box
public void addPerson(Person person){
person.add(person);
/*
*gets the lass element in the list and adds the first
*name of this specific element into the box
*/
box.addItem(person.get(person.size()-1).getFirstName());
}
}
public class Person{
String firstName,sureName;
public Person(String firstName, String sureName){
this.firstName = firstName;
this.sureName = sureName;
}
public String getFirstName(){
return this.firstName;
}
public String getSureName(){
return this.sureName;
}
}

Class mypack.pages.User has been transformed and may not be directly instantiated

I am trying to display a grid with tapestry based on this Tutorial, but i'm getting this error Class mypack.pages.User has been transformed and may not be directly instantiated
those are my classes User
public class User {
#NonVisual
private long id;
private String firstName;
private String lastName;
private int age;
public long getId() { return id; }
public void setId(long id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public User(long id, String firstName, String lastName, int age) {
super();
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
}
Bellilpage.java
public class Bellilpage {
#Property
private User user;
public List<User> getUsers() {
List<User> dd= new ArrayList<User>();
for(int x=0;x<1;x++)
{
Random rand = new Random();
long d= rand.nextInt(50);
User myuser = new User(d, "Name N° "+d, "lastName N "+d, (int) (d+15));
dd.add(myuser);
}
return dd; }
}
and finally this is how i try to display the grid in the web page
Bellilpage.tml
<html t:type="layout" title="tapestrythetest Index"
t:sidebarTitle="Framework Version"
xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd"
xmlns:p="tapestry:parameter">
<!-- A Zone is a component that can be updated in place, triggered by other components. -->
<t:zone t:id="zone">
<h1>List Users</h1>
<t:grid source="users" row="user">
<p:lastNameCell>
${user.lastname}
</p:lastNameCell>
</t:grid>
</t:zone>
<p:sidebar>
</p:sidebar>
</html>
Why am i gtting this error when i open Bellilpage.tml?
You are getting the error because mypack.pages is a T5 controlled package. Move your User class to a different package, e.g. to mypack.entities. More info at Component Classes, specifically the Component Packages section.

How to update a value stored in an Object on "Update" button click - Android?

I have the following class for an android application.
public class AccountVO
{
private String id;
private String username;
private String password;
private String email;
private String firstName;
private String lastName;
public AccountVO(String tempID, String tempUserName, String tempPassword, String tempEmail, String tempFirstName, String tempLastName)
{
this.id = tempID;
this.username = tempUserName;
this.password = tempPassword;
this.email = tempEmail;
this.firstName = tempFirstName;
this.lastName = tempLastName;
}
public String getId()
{
return id;
}
public String getUserName()
{
return username;
}
public String getEmail()
{
return email;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
}
I create the following objects in an activity.
AccountVO userAccount = new AccountVO("1", "scott", "password", "scott#mail.com", "Scott", "James");
AccountVO userAccount2 = new AccountVO("2", "john", "password", "jsmith#mail.com", "John", "Smith");
I have another activity where I retrieve the values from the objects which I created above and display them in EditText fields. Suppose I change the data in the fields and click on the "Update" Button, can anyone please tell as to how to update the values in my old AccountVO object? For Example: If I change the email via the edittitext field in "userAccount" AccountVO object (to say scott#abc.com), How to update that value in the same object?
Write a setter for each of the fields you have a getter for, like so:
public void setLastName(String lastName) {
this.lastName = lastName;
}
Then, call the setter in the Update function:
public void Update() {
userAccount.setLastName(editText.getText().toString());
}

Categories