3

here is my entire class. I read data from a text file, put them into an aeeaylist. then from that array list i want to show the data on a JTable, when the specific method is called.But is doesnt show anything

   /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author George
 */
import java.awt.*;
import java.util.ArrayList;
//import java.io.FileInputStream;
//import java.io.FileNotFoundException;
//import java.io.EOFException;
//import java.io.IOException;
//import java.io.ObjectInputStream;
/*import java.io.File;
import java.lang.IllegalStateException;
import java.util.NoSuchElementException;
import java.util.Scanner;
import javax.swing.JOptionPane;*/
import java.io.*;
//import java.util.Locale;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;



public class Company extends JFrame  {
   private  ArrayList<Employee> emp=new ArrayList<Employee>();


 //Employee[] list=new Employee[7];



 public void getEmployees(Employee emplo){

     emp.add(emplo);
 }


 /*public void openTxt(){
     try {
         Scanner input=new Scanner(new File("Employees.txt"));
     }
     catch(FileNotFoundException e){
       JOptionPane.showMessageDialog(null, "File Not Found.");
       System.exit(1);
     }
     }*/

 public void doRead() throws Exception{
             //ArrayList<Employee> emp=new ArrayList<Employee>() ;
        //Employee[] emp=new Employee[7];
         //read from file
        File data = new File("src/Employees.txt");
        BufferedReader read = new BufferedReader(new FileReader(data));
        String input;
        int i = 0;
        //int salesmen = 0;
        while ((input = read.readLine()) != null) {
            String [] lineParts = input.split(",");

            /**
             * the following block converts some of the strings inputted to
             * the appropriate vartypes.
             */

            String EmpNo=(lineParts[0]);
            String type=lineParts[10];
            String PostalCode = (lineParts[5]);
            int phone = Integer.parseInt(lineParts[6]);
            short DeptNo = (short) Integer.parseInt(lineParts[8]);
            double Salary;
            short card = (short) Integer.parseInt(lineParts[11]);
            int dtype=0;

            if(type.equals("FULL TIME")){
                dtype=1;
            }
            else if(type.equals("SELLER")){
                dtype=2;
            }
            else
                dtype=3;

            /**
             *  Creates employee instances depending on their type of employment
             *  (fulltime=1, parttime=3, salesman=2)
             */
            switch (dtype) {
                case 1 :
                    //empNo,firstname, lastname, address, city, PostalCode, phone,
                    //email, deptcode,Jobtype,  salary, TimecardId, hoursW

                    Salary = Double.parseDouble(lineParts[10]);
                    emp.add(new FullTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
                            lineParts[4], PostalCode, phone,
                            lineParts[7], DeptNo,type,Salary, card, 0.0));

                    i++;
                    break;
                case 2 :
                    Salary = Double.parseDouble(lineParts[10]);
                    ArrayList<Orders> orders=new ArrayList<Orders>();
                    Salary = Double.parseDouble(lineParts[10]);
                    emp.add(new Salesman(EmpNo,lineParts[1], lineParts[2], lineParts[3],
                            lineParts[4], PostalCode, phone,
                            lineParts[7], DeptNo,type,Salary, card, 0.0, orders));
                    i++;
                    break;
                case 3 :
                    Salary = Double.parseDouble(lineParts[10]);
                    emp.add(new PartTimeEmployee(EmpNo,lineParts[1], lineParts[2], lineParts[3],
                            lineParts[4], PostalCode, phone,
                            lineParts[7], DeptNo,type,Salary, card, 0.0));

                    i++;
                    break;
                default :
                    break;
           }


        }

 }
 public ArrayList<Employee> getArray(){
     return emp;
 }

 //test methodos gia tin proti epilogi-den deixnei tipota omws sto JTable ????
 public /*JTable */ void getOptionA(){
     ArrayList<Employee> list=getArray();
     /*String[] columnNames = {"Code","First Name","Last Name","Address","Cisty","Postal Code","Phone","Email",
                                "Dept Code","Salary","Time Card","Hours"};*/
    /* Object[][] data;
     */
     JTable table = new JTable();
DefaultTableModel model = new DefaultTableModel();
table.setModel(model);
model.setColumnIdentifiers(new String[] {"Code","First Name","Last Name","Address","City","Postal Code","Phone","Email",
                                "Dept Code","Salary","Time Card","Hours"});
     for( Employee current : list){
         model.addRow(new Object[] {current.getCode(),current.getName(),current.getSurname(),
                                    current.getAddress(),current.getCity(),current.getTK(),
                                    current.getPhone(),current.getMail(),current.getDeptCode(),
                                    current.getSalary(),current.getCard(),current.getHours()
         });

     }

     /*JScrollPane scrollPane = new JScrollPane(table);
     table.setFillsViewportHeight(true);*/
     //return table;
     table.setPreferredScrollableViewportSize(new Dimension(500,50));
     table.setFillsViewportHeight(true);
     JScrollPane scrollPane = new JScrollPane(table);
     add(scrollPane);



 }
 public  void showOptionA(){
     getOptionA();
     Company gui =new Company();
     gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     gui.setVisible(true);
     gui.setSize(600, 400);

 }

 }

I call showOptionA() from a JButton located on another JFrame Class.

private void showEmployeesActionPerformed(java.awt.event.ActionEvent evt) {                                              
    Results showEmp=new Results();
    //showEmp.setVisible(true);
    //showEmp.setOptions(1);
    Company company=new Company();
    /*JTable table=company.getOptionA();
    JScrollPane scrollPane = new JScrollPane(table);
 table.setFillsViewportHeight(true);
 scrollPane.setViewportView(table);
 table.setVisible(true);*/
    company.showOptionA();
}  

Basically i have a "main"JFrame with different options, and each button,representing a different option, calls the appropriate option method from Company Class.

When i click on the button "Show Employees Status". i want it to show the JTable above. Instead a new Frame opens but is blank??

EDIT: if i change showOptionA() to static, and then just call it inside showEmployeesActionPerformed , ( which is located in class PayrollForm)

public static void showOptionA(){

     Company gui =new Company();
             gui.getOptionA();
     gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     gui.setVisible(true);
     gui.setSize(600, 400);

 }

i now see the columns but with no data(empty)

George
  • 433
  • 2
  • 10
  • 25

4 Answers4

2

This has nothing to do with calling revalidate as recommended by another and likely has all to do with calling a method on the wrong object. In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. The key is to call this method on the proper reference, on the visualized GUI. You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. This can be done via a setCompany method:

setCompany(Company company) {
  this.company = company);
}

or via a constructor parameter.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • so if i understand i must create a setCompany method in Company class and then call that method from the showEmployeesActionPerformed ? or is it the other way around? I create The object of class Company in the method of showEmployeesActionPerformed, to gain access to Company's methods – George Dec 17 '10 at 15:36
  • I tried also this: i switched public void showOptionA() to public static void main(String args[]) , to see if it will run smoothly from only inside the Company class, but again, only column names appear. The table behaves as empty ? – George Dec 17 '10 at 16:03
  • No, you don't need setCompany in the Company class. Instead you need a setCompany class in any other outside class that will be calling the Company object's methods. This way you can make sure that these other classes are calling methods on the *right* Company object, the one that is being displayed. – Hovercraft Full Of Eels Dec 17 '10 at 18:36
  • i am sorry if i'm beeing annoying, or i sound "dumb". but i just cant find the reason to put a setter method in ex:PayrollForm(the form with the buttons). Even if i set the field : private Company company; ,as a local variable in PayrollForm class , to be able to call any method from Company class, i still need to initialize that variable, or create a new Company variable =new Company(); I'm not sure i get what you are trying to tell me. Maybe i mess at where the setter method should be called?? Can you give an example? I mean ok i put the method in PayrollForm Class. Then what do i do next ? – George Dec 17 '10 at 21:52
  • in PayrollForm : private Company company; public void setCompany(Company company) { this.company = company; } Then what do you add in the showEmployeesActionPerformed method? – George Dec 17 '10 at 21:53
  • If you have a Company JFrame showing, and inside of some actionPerformed method create a new Company object by calling new Company(), then all the actions performed on the new Company object will have no effect on the GUI that's displaying because they are two completely distinct separate objects. – Hovercraft Full Of Eels Dec 17 '10 at 22:36
  • The only way to call methods on a Company object and make sure that it has an effect on the currently displayed Company object is to be sure that they are one and the same -- that the Company object you are calling methods on is the same as the one that is displaying. – Hovercraft Full Of Eels Dec 17 '10 at 22:37
  • 1
    If your Control object is in its own stand alone class, then to make sure that you have a correct reference to the Company that is displaying you need to give that control class (the one with actionPerformed or similar methods) a Company variable, and set that variable with a reference to the displayed Company object via a setCompany(Company company) method or by passing a Company object into its constructor. I'm not sure how else to explain this, sorry. – Hovercraft Full Of Eels Dec 17 '10 at 22:37
1

I think the reason is your method showOptionA():

first you add your JTable and Model to your Company Object, which is your Frame. But right after it, you create a new Company Object, set the wanted Frame settings and show that object instead of your first Company object, where the table is.

You just could leave the gui thing out, and set DefaultCloseOperation directly on your Company object and set it visible true.

Some other suggestions: You also should set the size of your frame, before you set it visible true. And getters normally just give back the related object, instead of putting it on some list. Might be there are some more mistakes in it, but it should at least show your table.

crusam
  • 6,140
  • 6
  • 40
  • 68
0

Call revalidate() after adding anything to JTable (or its model).

Paweł Dyda
  • 18,366
  • 7
  • 57
  • 79
  • Why are you recommending this? There is no need to call revalidate after adding or changing the model as long as you fire the correct change method to notify the table model's listeners -- and even this isn't necessary if you are using a DefaultTableModel. – Hovercraft Full Of Eels Dec 17 '10 at 14:22
  • Agreed you don't need to call revalidate() after updating the model. However, the code does create a new table and scrollpane and then it adds the scrollpane to the frame. So yes you need the revalidate after adding the scrollpane to the frame. So right idea, wrong reason, assuming of course the method is executed and the TableModel is actually recreated. – camickr Dec 17 '10 at 16:25
0

Ok problem Solved!. The problem was in getOptionA() method. i set the model of the Jtable, but not the option to be visible. SO thats why it appeared empty. I corrected this by moving

try {
     //try to read from text file
     doRead();
     }
     catch(Exception e){
        JOptionPane.showMessageDialog(null, "An Exception has Occured! The application will now close.");
        System.exit(0);
     }

table.revalidate();


    add(scrollPane);
     setVisible(true);
     setSize(600, 400);

up,from showOptionA, up to getOptionA() method. By doing this showOptionA becomes useless(and thus i deleted it). Now i call getOptionA from the showEmployeesActionPerformed and its all ok :). Thanks to all people who replied to my wuestion, and special thanks to Hovercraft Full Of Eels . He helped me undeestand why the table wasnt appearing the way i wanted it to

George
  • 433
  • 2
  • 10
  • 25