JTable 没有显示任何内容?

发布于 2024-10-08 06:43:53 字数 6889 浏览 0 评论 0原文

这是我全班同学的情况。我从文本文件中读取数据,将它们放入 aeeaylist 中。然后,当调用特定方法时,我想从该数组列表中显示 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);

 }

 }

我从位于另一个 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();
}  

基本上我有一个带有不同选项的“主”JFrame,每个按钮代表一个不同的选项,从公司类调用适当的选项方法。

当我单击“显示员工状态”按钮时。我希望它显示上面的 JTable。相反,会打开一个新框架,但它是空白的?

编辑:如果我将 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);

 }

我现在可以看到列,但没有数据(空)

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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

自此以后,行同陌路 2024-10-15 06:43:53

这与按照另一个人的建议调用 revalidate 无关,并且可能与在错误的对象上调用方法有关。在 showEmployeesActionPerformed 方法中,您创建一个新的 Company 对象,该对象未可视化。关键是在可视化 GUI 上的正确引用上调用此方法。您可以通过将对可视化 GUI 对象的引用传递到要调用其方法的类来实现此目的。这可以通过 setCompany 方法

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

或通过构造函数参数来完成。

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.

离去的眼神 2024-10-15 06:43:53

我认为原因是你的方法 showOptionA():

首先将你的 JTable 和模型添加到你的公司对象,这是你的框架。但紧接着,您创建一个新的公司对象,设置所需的框架设置并显示该对象,而不是表所在的第一个公司对象。

您可以忽略 gui 的事情,直接在 Company 对象上设置 DefaultCloseOperation 并将其设置为可见 true。

其他一些建议:
在将其设置为可见之前,您还应该设置框架的大小。
getter 通常只是返回相关对象,而不是将其放入某个列表中。
可能还有更多错误,但它至少应该显示您的表格。

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.

十年不长 2024-10-15 06:43:53

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

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

心在旅行 2024-10-15 06:43:53

好的问题解决了!问题出在 getOptionA() 方法中。
我设置了 Jtable 的模型,但没有设置可见的选项。这就是为什么它看起来是空的。我通过

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);

从 showOptionA 向上移动到 getOptionA() 方法来纠正此问题。通过这样做,showOptionA 变得毫无用处(因此我删除了它)。现在我从 showEmployeesActionPerformed 调用 getOptionA 并且一切正常:)。感谢所有回复我问题的人,特别感谢充满鳗鱼的气垫船。他帮助我理解了为什么桌子没有按照我想要的方式显示

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文