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;
}
}
Related
I have class Student, that has first name, last name and age, and a method to print the name and the age of the student.
public class Student {
private String firstName;
private String LastName;
private int age;
}
Student() {}
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
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 void printInfoStudent(){
System.out.println("Student: " + firstName + " " + lastName + ", " + age);
}
And I have a second class Professor, that has first name, last name, and university. And I have a method to print the info about the professor.
public class Professor {
private Student firstName;
private Student lastName;
private String uni;
}
Professor() {
}
public Professor(Student firstName, Student lastName, String uni) {
this.firstName = firstName;
this.lastName = lastName;
this.uni = uni;
}
public Student getFirstName() {
return firstName;
}
public void setFirstName(Student firstName) {
this.firstName = firstName;
}
public Student getLastName() {
return lastName;
}
public void setLastName(Student lastName) {
this.lastName = lastName;
}
public String getUni() {
return uni;
}
public void setUni(String uni) {
this.uni = uni;
}
public void printInfo(){
System.out.println("Professor: " + firstName + " " + lastName + ", uni: " + university);
}
And in the main class I create two objects.
Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford");
printInfo.p();
printInfoStudent.s();
And it's showing me an error: String cannot be converted to Student, can someone explain why is that, and how should I fix this?
You've created the objects properly but are not calling their functions properly.
Student s = new Student("John", "John", 24);
Professor p = new Professor("Johnny", "Johnny", "Oxford");
p.printInfo()
s.printInfoStudent();
You need to name the instance first then specify the method inside to call after the dot.
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"));
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.
This question already has an answer here:
When to use JavaFX properties setter and getter, instead of using the property directly
(1 answer)
Closed 7 years ago.
What is the difference between these two lines?
return firstName.get();
return firstName;
When should I use one or the other?
Here you have two classes where those lines are used:
package application.model;
import javafx.beans.property.StringProperty;
public class Employee {
private int id;
private String firstName,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;
}
public StringProperty firstNameProperty() {
return firstName;
}
}
package ch.makery.address.model;
import java.time.LocalDate;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
/**
* Model class for a Person.
*
* #author Marco Jakob
*/
public class Person {
private final StringProperty firstName;
private final StringProperty lastName;
private final StringProperty street;
private final IntegerProperty postalCode;
private final StringProperty city;
private final ObjectProperty<LocalDate> birthday;
/**
* Default constructor.
*/
public Person() {
this(null, null);
}
/**
* Constructor with some initial data.
*
* #param firstName
* #param lastName
*/
public Person(String firstName, String lastName) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
// Some initial dummy data, just for convenient testing.
this.street = new SimpleStringProperty("some street");
this.postalCode = new SimpleIntegerProperty(1234);
this.city = new SimpleStringProperty("some city");
this.birthday = new SimpleObjectProperty<LocalDate>(LocalDate.of(1999, 2, 21));
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public String getStreet() {
return street.get();
}
public void setStreet(String street) {
this.street.set(street);
}
public StringProperty streetProperty() {
return street;
}
public int getPostalCode() {
return postalCode.get();
}
public void setPostalCode(int postalCode) {
this.postalCode.set(postalCode);
}
public IntegerProperty postalCodeProperty() {
return postalCode;
}
public String getCity() {
return city.get();
}
public void setCity(String city) {
this.city.set(city);
}
public StringProperty cityProperty() {
return city;
}
public LocalDate getBirthday() {
return birthday.get();
}
public void setBirthday(LocalDate birthday) {
this.birthday.set(birthday);
}
public ObjectProperty<LocalDate> birthdayProperty() {
return birthday;
}
}
In short: It depends on the context.
You may only use .get() when the object has a method get. String objects are very similar to primitives, they are a value and as such can be returned directly (they don't have a get method at all).
Here, StringProperty is a wrapper around (assumedly) a String, meaning if you were to return firstName; from the Person class, you would get a StringProperty instance, not a String - which most likely cannot be used in most operations. So, you return whichever datatype you need.
Note that if you were working with strings in both the source and destination classes, you could just return the value directly, it's already in usable form.
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.