Make a JTable in Swing with Response of GET REST Webservices - java

i have a Swing App, i use Retrofit to Consume Rest Service in my Swing App.
Now I want to Populate the Response of m Get Service in a Jtable.
Thais the List for all Employees that i get using Retrofit
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
I want to Populate that in a Jtable
That is My Employee Modell
public class Employee {
private long empno;
private String ename;
private String job;
private Date hiredate;
private long mgr;
private long sal;
private long deptno;
public long getEmpno() {
return empno;
}
public void setEmpno(long empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public String getJob() {
return job;
}
public void setJob(String job) {
this.job = job;
}
public Date getHiredate() {
return hiredate;
}
public void setHiredate(Date hiredate) {
this.hiredate = hiredate;
}
public long getMgr() {
return mgr;
}
public void setMgr(long mgr) {
this.mgr = mgr;
}
public long getSal() {
return sal;
}
public void setSal(long sal) {
this.sal = sal;
}
public long getDeptno() {
return deptno;
}
public void setDeptno(long deptno) {
this.deptno = deptno;
}
#Override
public String toString() {
return empno + " \t"
+ ename + " \t"
+ deptno + " \t"
+ mgr + " \t"
+ sal + " \t"
+ hiredate.toString();
}
}
Here i want to Populate the Table
public void updateConsole() {
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
StringBuilder builder = new StringBuilder();
for (Employee employee : employees) {
builder.append(employee.toString());
columns.add("col1");
columns.add("col2");
columns.add("col3");
TableModel tableModel = new DefaultTableModel(employees.toArray(new Object[][] {}), columns.toArray());
table = new JTable(tableModel);
builder.append("\n");
}
textPane.setText(builder.toString());
}
And i have that Error
java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at java.util.Arrays.copyOf(Arrays.java:3213)
at java.util.ArrayList.toArray(ArrayList.java:407)
at View.Console.updateConsole(Console.java:43)
at application.Main.updateConsole(Main.java:54)
Somebody can help me please?

it Works fine now. I make it like so
public void updateConsole() {
ArrayList<Employee> employees = EmployeesData.getInstance().getEmployees();
Object[] columnNames = { "Deptno", "Empno", "Name","Hiredate","Job","Management","Salary"};
DefaultTableModel model = new DefaultTableModel(new Object[0][0], columnNames);
StringBuilder builder = new StringBuilder();
for (Employee employee : employees) {
//builder.append(employee.toString());
Object[] o = new Object[7];
o[0] = employee.getDeptno();
o[1] = employee.getEmpno();
o[2] = employee.getEname();
o[3] = employee.getHiredate();
o[4] = employee.getJob();
o[5] = employee.getMgr();
o[6] = employee.getSal();
model.addRow(o);
//builder.append("\n");
}
//textPane.setText(builder.toString());
table.setModel(model);
}

Related

Age filter in Java with ArrayList

I want to make a method that tells me who is the oldest person in the ArrayList and who is the youngest person. The method will receive the arraylist that i want to apply the method, i have 3 in my code, each one is an contact list.
The method is suppose to return the name of the person, but i don't know how to do it. Familia, Profissional and Amigos are my arraylists and "idade" = age and "nome" = name.
package com.company;
public class Contato {
public String nome;
public int idade;
public String sexo;
public String profissao;
public String telefone;
public String email;
public Contato(String nome, int idade, String sexo, String profissao, String telefone, String email) {
this.nome = nome;
this.idade = idade;
this.sexo = sexo;
this.profissao = profissao;
this.telefone = telefone;
this.email = email;
}
#Override
public String toString() {
return "" +
nome + ',' +
idade + " anos de idade, " +
"do sexo " + sexo + ',' +
profissao + ',' +
" telefone nÂș " + telefone + ", " +
"e-mail:" + email;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public int getIdade() {
return idade;
}
public void setIdade(int idade) {
this.idade = idade;
}
public String getSexo() {
return sexo;
}
public void setSexo(String sexo) {
this.sexo = sexo;
}
public String getProfissao() {
return profissao;
}
public void setProfissao(String profissao) {
this.profissao = profissao;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
package com.company;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
public class GestaoContatos extends Contato {
ArrayList<Contato> Familia = new ArrayList();
ArrayList<Contato> Amigos = new ArrayList();
ArrayList<Contato> Profissional = new ArrayList();
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
}
public void adicionaContato(String nomeAgenda, Contato contato) {
if( nomeAgenda == "Familia"){
Familia.add(contato);
} else
if(nomeAgenda == "Amigos"){
Amigos.add(contato);
} else
if(nomeAgenda == "Profissional") {
Profissional.add(contato);
} else
System.out.println("IndispnĂ­vel");
}
public void eliminaContato(String nomeContato) {
for(int i = 0; i < Familia.size(); i++) {
if(getFamilia().contains(nomeContato)) {
Familia.remove(nomeContato);
}
}
}
public void printaLista(String nomeAgenda){
if(nomeAgenda.equals("Familia")) {
Familia.forEach(System.out::println);
}
if(nomeAgenda.equals("Amigos")) {
Amigos.forEach(System.out::println);
}
if(nomeAgenda.equals("Profissional")) {
Profissional.forEach(System.out::println);
}
else {
throw new RuntimeException("Opcao invalida");
}
}
public void tooString() {
var contatos = new ArrayList<Contato>();
Familia.forEach(it -> contatos.add(it));
Amigos.forEach(it -> contatos.add(it));
Profissional.forEach(it -> contatos.add(it));
System.out.println(contatos.toString());
}
public void olderPerson(String nomeAgenda){
int i = 0;
if (nomeAgenda.equals("Amigos")) {
for (i = 0; Familia.size(); i++) {
Familia.stream().filter();
}
}
}
public void geraListaBinaria() throws IOException {
var file = new File("C:\\Users\\Jorge Luiz\\Desktop\\contatos.txt");
var writer = new FileWriter(file.getName());
writer.write(this.getProfissional().toString());
writer.write(this.getFamilia().toString());
writer.write(this.getProfissional().toString());
writer.close();
}
public ArrayList<Contato> getFamilia() {
return Familia;
}
public void setFamilia(ArrayList<Contato> familia) {
Familia = familia;
}
public ArrayList<Contato> getAmigos() {
return Amigos;
}
public void setAmigos(ArrayList<Contato> amigos) {
Amigos = amigos;
}
public ArrayList<Contato> getProfissional() {
return Profissional;
}
public void setProfissional(ArrayList<Contato> profissional) {
Profissional = profissional;
}
}
If you want to return oldest person in one list:
public Contato oldestPerson(String nomeAgenda){
return Familia.stream()
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}
For all lists you can do:
public Contato oldestPerson(){
return Stream.of(Familia, Amigos, Profissional)
.flatMap(Collection::stream) // flatting to one long stream
.filter(c -> c.getNome().equals(nomeAgenda)) // contatos named nomeAgenda
.max(Comparator.comparingInt(Contato::getIdade))
.get();
}
EDIT
Based on the comment, we should change a couple of things to achieve what you want. First, we should define a Map<String, List<Contato>> and populate it in the constructor:
private Map<String, List<Contato>> contatoGroups;
private static final String familiaKey = "Familia";
private static final String amogisKey = "Amigos";
private static final String profissionalKey = "Profissional";
public GestaoContatos(Contato c) {
super(c.nome, c.idade, c.sexo, c.profissao, c.telefone, c.email);
contatoGroups.put(familiaKey, new ArrayList<>());
contatoGroups.put(amogisKey, new ArrayList<>());
contatoGroups.put(profissionalKey, new ArrayList<>());
}
(Consider using enum instead of String as key in the map)
Then wherever you want to get a group, for example: Familia, you should do:
List<Contato> contatoes = contatoGroups.get(familiaKey);
And then we should change the oldestPerson() like this:
public Contato oldestPerson(String nomeAgenda){ // nomeAgenda could be "Familia", "Amigos"...
List<Contato> selectedGroup = contatoGroups.get(nomeAgenda);
return selectedGroup.stream()
.max(Comparator.comparingInt(Contato::getIdade)) // take oldest
.get();
}

How to print all DirectorNames or ProducerNames etc alphabetically reading from a text file

public void alphabeticalListing()
{
BufferedReader br = null;
List<String> lineList = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(wishlistname + ".txt"));
String line;
while((line = br.readLine())!=null)
{
lineList.add(line);
}
Collections.sort(lineList);
for(String output : lineList) {
System.out.println(output);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
The file Contains Movie Details...
Example:
MovieName:DirectorName:ProducerName:Rating:Review
Terminator: Arfath: Khalid : 8 : VeryGood
Hangover : John : Lucas : 7 : NotBad
Jumanji : Rock : Brock : 9 : Good
I want to select ProducerName Column and do SOP in alphabetically like,
Output:
Brock
Khalid
Lucas
You can use java Compartor for sorting by creating Movie as model class. You can achieve this using below code:
public static void readDataFromFile(String filePath) throws FileNotFoundException
{
List<Movie> movies = new ArrayList<Movie>();
File file = new File(filePath);
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
{
String txtLine = sc.nextLine();
//Extract data from single from txt file row
String[] data = txtLine.split(":");
Movie movie = new Movie(data[0], data[1], data[2], data[3], data[4]);
//Add to movies list
movies.add(movie);
}
System.out.println("Unsorted-----------");
System.out.println(movies);
System.out.println("Sorting by director-----------");
Collections.sort(movies, new DirectorSorter());
System.out.println(movies);
System.out.println("Sorting by producer-----------");
Collections.sort(movies, new ProducerSorter());
System.out.println(movies);
}
public static class Movie
{
private String name;
private String director;
private String producer;
private String rating;
private String review;
public Movie(){}
public Movie(String name, String director, String producer, String rating, String review){
this.name = name;
this.director = director;
this.producer = producer;
this.rating = rating;
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getProducer() {
return producer;
}
public void setProducer(String producer) {
this.producer = producer;
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
#Override
public String toString() {
return "Movie : " + name + " - " + director + " - " + producer + " - " + rating + " - " + review + "\n";
}
}
public static class DirectorSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getDirector().compareTo(o2.getDirector());
}
}
public static class ProducerSorter implements Comparator<Movie>{
#Override
public int compare(Movie o1, Movie o2) {
return o1.getProducer().compareTo(o2.getProducer());
}
}

Can't get ComboboxTableCell in javafx app

I am trying to show a combobox for each record that is fetched from database,but unfortunatley i can't get any combobox in expected column.
Here is code for my model class:
public class Employee {
private final int id;
private final SimpleStringProperty ename;
private final SimpleStringProperty ecnic;
private final SimpleDoubleProperty ebalance;
private final SimpleDoubleProperty etotalpaid;
private SimpleStringProperty estatus;
public Employee(int id, String ename, String ecnic, Double ebalance,
Double etotalpaid, String estatus) {
super();
this.id = id;
this.ename = new SimpleStringProperty(ename);
this.ecnic = new SimpleStringProperty(ecnic);
this.ebalance = new SimpleDoubleProperty(ebalance);
this.etotalpaid = new SimpleDoubleProperty(etotalpaid);
this.estatus = new SimpleStringProperty(estatus);
}
public String getEstatusproperty() {
return estatus.get();
}
public String getEstatus() {
return estatus.get();
}
public void setEstatus(String estatus) {
this.estatus = new SimpleStringProperty(estatus);
}
public int getId() {
return id;
}
public String getEname() {
return ename.get();
}
public String getEcnic() {
return ecnic.get();
}
public Double getEbalance() {
return ebalance.get();
}
public Double getEtotalpaid() {
return etotalpaid.get();
}
}
Here is code for my method that i call to fetch data from database..
public void attendence() throws SQLException{
employeelist = FXCollections.observableArrayList();
ename.setCellValueFactory(new PropertyValueFactory<Employee,String>("ename"));
ecnic.setCellValueFactory(new PropertyValueFactory<Employee,String>("ecnic"));
ebalance.setCellValueFactory(new PropertyValueFactory<Employee,Double>("ebalance"));
etotalpaid.setCellValueFactory(new PropertyValueFactory<Employee,Double>("etotalpaid"));
estatus.setCellValueFactory(new PropertyValueFactory<Employee,String>("estatus"));
estatus.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), attendenceoptions));
estatus.setOnEditCommit(
new EventHandler<CellEditEvent<Employee, String>>() {
#Override
public void handle(CellEditEvent<Employee, String> t) {
((Employee) t.getTableView().getItems().get(t.getTablePosition().getRow())).setEstatus(t.getNewValue());
};
});
estatus.setEditable(true);
stmt = conn.createStatement();
sql = "select * from employe";
rs = stmt.executeQuery(sql);
while(rs.next()){
employeelist.add(new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDouble(5),rs.getDouble(6),"Present"));
employeetable.setItems(employeelist);
}
stmt.close();
rs.close();
}
}
Added this in method to solve issue.
employeetable.setEditable(true);

GWT mix two objects in my TreeViewModel

I Have this Model :
1) Team :
public class Team {
private String nom ;
private Employee leader ;
private List<Employee> members = new ArrayList<Employee>();
private List<Person> persons = new ArrayList<Person>();
public Team() {
}
public Team(String nom, Employee leader, List<Employee> members, List<Person> persons) {
this.nom = nom;
this.leader = leader;
this.members = members;
this.persons = persons;
}
public Team(String nom) {
this.nom = nom;
}
public Employee addEmployee (Employee employee) {
members.add(employee);
return employee;
}
public Person addPerson (Person person) {
persons.add(person);
return person;
}
public List<Person> getPersons() {
return persons;
}
public void setPersons(List<Person> persons) {
this.persons = persons;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public Employee getLeader() {
return leader;
}
public void setLeader(Employee leader) {
this.leader = leader;
}
public List<Employee> getMembers() {
return members;
}
public void setMembers(List<Employee> members) {
this.members = members;
}
#Override
public String toString() {
return "Team{" +
"nom='" + nom + '\'' +
", leader=" + leader +
", members=" + members +
'}';
}
public Team(int i){
this.setNom("team"+i);
this.setLeader(new Employee("MoMo" + i, "dd" + i));
this.addEmployee(new Employee("mehdi" + i, "dd" + i));
this.addEmployee(new Employee("albert" + i+1,"dd"+ i));
this.addEmployee(new Employee("lolo" + i+2,"dd"+ i));
this.addPerson(new Person("Person" + i));
this.addPerson(new Person("Person" + i+1 ));
this.addPerson(new Person("Person" + i+2 ));
}
2)
public class Employee {
private String cin;
private String nom;
private String prenom;
3)
public class Person {
private String address;
private String name;
public Person(){
}
public Person(String name) {
this.name = name;
}
public Person(String name, String address) {
this.name = name;
this.address = address;
}
public String getAddress() {
return address;
}
public String getName() {
return name;
}
}
I want to build a GWT TreeViewModel like the following :
Team => (i want to have my list of persons and my list of employees mixed)
Here is my TreeViewModel
public class EmployeeTreeModel implements TreeViewModel {
private final List<Team> teamList;
private final SingleSelectionModel<Employee> selectionModel
= new SingleSelectionModel<Employee>();
public EmployeeTreeModel() {
teamList = new ArrayList<Team>();
{
for (int i = 0; i < 5 ; i++) {
teamList.add(new Team(i) );
}
}
}
#Override
public <T> NodeInfo<?> getNodeInfo(T value) {
if (value == null) {
ListDataProvider<Team> dataProvider
= new ListDataProvider<Team>(teamList);
Cell<Team> cell = new AbstractCell<Team>() {
#Override
public void render(Context context, Team value, SafeHtmlBuilder sb) {
if (value != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(value.getNom());
}
}
};
return new DefaultNodeInfo<Team>(dataProvider, cell);
}
else if (value instanceof Team) {
ListDataProvider<Employee> dataProvider
= new ListDataProvider<Employee>(
((Team) value).getMembers());
Cell<Employee> cell =
new AbstractCell<Employee>() {
#Override
public void render(Context context, Employee employee, SafeHtmlBuilder sb) {
if (employee != null) {
sb.appendHtmlConstant(" ");
sb.appendEscaped(employee.getNom());
}
}
};
return new DefaultNodeInfo<Employee>(dataProvider, cell,selectionModel, null);
}
return null;
}
#Override
public boolean isLeaf(Object o) {
if (o instanceof Employee) {
return true;
}else if(o instanceof Person){
return true;
}
else return false;
}
}
in my actual code I can't mix Employees data and Person's Data because two different objects
Any way to do that ?
A listDataProvider who brings two Objects maybe ?

array in a separate class other than main method/class

I keep getting this error, its about needing braces after the array decleration.
I do not know what to do about this. I want to make an array that is not in my main method. I want the array to be supertype populated with subclass.
Here is my code
public class ArrayTest {
Employee [] employees = new Manager[2];
employees[0]= new Manager("Thomas", "Cummings");
}
public class Manager extends Employee{
private int employees;
public Manager() {
super();
employees = 0;
}
public Manager(int employees) {
super();
this.employees = employees;
}
public Manager(String f_name, String l_name) {
super(f_name, l_name);
}
public Manager(String f_name, String l_name, int employees) {
super(f_name, l_name);
this.employees = employees;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public void setManager(String f_name, String l_name){
this.setF_name(f_name);
this.setL_name(l_name);
}
public void setManager(String f_name, String l_name, int employees){
this.setF_name(f_name);
this.setL_name(l_name);
this.employees = employees;
}
#Override
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id() +
"\nNum of employees " + getEmployees();
}
}
public class Employee {
private String f_name, l_name;
private static long emp_id = 001;
public Employee(){
f_name = "";
l_name = "";
emp_id ++;
}
public Employee(String f_name, String l_name) {
this.f_name = f_name;
this.l_name = l_name;
emp_id ++;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public long getEmp_id() {
return emp_id;
}
public void setEmp_id(long emp_id) {
Employee.emp_id = emp_id;
}
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id();
}
}
The reason of error is the following statement:
employees[0]= new Manager("Thomas", "Cummings");
as you cannot put executable statements outside of code blocks(methods, blocks, constructors) in a java class.
One way to resolve this problem is by moving the initialization statement in a constructor:
public class ArrayTest {
Employee [] employees = new Manager[2];
public ArrayTest() {
employees[0]= new Manager("Thomas", "Cummings");
}
}
employees[0]= new Manager("Thomas", "Cummings");
this is an statement which needs to be placed in proper executable block (method, constructor, initialization block)

Categories