简体   繁体   English

JTable没有显示任何内容?

[英]JTable does not show anything?

here is my entire class. 这是我的全班。 I read data from a text file, put them into an aeeaylist. 我从文本文件中读取数据,将它们放入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 然后从那个数组列表我想在JTable上显示数据,当调用特定的方法时。但是没有显示任何东西

   /*
 * 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. 我从另一个JFrame类的JButton调用showOptionA()。

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. 基本上我有一个具有不同选项的“主”JFrame,每个按钮代表一个不同的选项,从公司类调用适当的选项方法。

When i click on the button "Show Employees Status". 当我点击“显示员工状态”按钮时。 i want it to show the JTable above. 我想让它显示上面的JTable。 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) 编辑:如果我将showOptionA()更改为静态,然后在showEmployeesActionPerformed中调用它(它位于类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) 我现在看到列但没有数据(空)

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. 这与调用另一个推荐的revalidate无关,而且可能与调用错误对象上的方法有关。 In your showEmployeesActionPerformed method you create a new Company object, one that is not visualized. 在showEmployeesActionPerformed方法中,您将创建一个新的Company对象,该对象不可视化。 The key is to call this method on the proper reference, on the visualized GUI. 关键是在可视化GUI上的适当引用上调用此方法。 You do this by passing a reference to the visualized GUI object into the class that is wanting to call methods on it. 您可以通过将可视化GUI对象的引用传递给想要在其上调用方法的类来完成此操作。 This can be done via a setCompany method: 这可以通过setCompany方法完成:

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

or via a constructor parameter. 或者通过构造函数参数。

I think the reason is your method showOptionA(): 我认为原因是你的方法showOptionA():

first you add your JTable and Model to your Company Object, which is your Frame. 首先,将JTable和Model添加到您的公司对象,即您的框架。 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. 你可以放弃gui的东西,直接在你的Company对象上设置DefaultCloseOperation并将其设置为true。

Some other suggestions: You also should set the size of your frame, before you set it visible true. 其他一些建议:在将帧设置为true之前,还应设置帧的大小。 And getters normally just give back the related object, instead of putting it on some list. 而getter通常只是回馈相关对象,而不是将其放在某个列表中。 Might be there are some more mistakes in it, but it should at least show your table. 可能会有更多的错误,但至少应该显示你的表。

在向JTable(或其模型)添加任何内容后调用revalidate()。

Ok problem Solved!. 好的问题解决了! The problem was in getOptionA() method. 问题出在getOptionA()方法中。 i set the model of the Jtable, but not the option to be visible. 我设置了Jtable的模型,但不是可见的选项。 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. up,从showOptionA到getOptionA()方法。 By doing this showOptionA becomes useless(and thus i deleted it). 通过这样做showOptionA变得无用(因此我删除它)。 Now i call getOptionA from the showEmployeesActionPerformed and its all ok :). 现在我从showEmployeesActionPerformed调用getOptionA并且它全部正常:)。 Thanks to all people who replied to my wuestion, and special thanks to Hovercraft Full Of Eels . 感谢所有回复我的问题的人,特别感谢Hovercraft Full Of Eels。 He helped me undeestand why the table wasnt appearing the way i wanted it to 他帮助我不知道为什么桌子没有像我想要的那样出现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM