如何将JTable添加到JTabbedPane中?

时间:2017-11-18 12:56:36

标签: java user-interface jtable jtabbedpane

我正在编写一个GUI,显示800个学生的表格,其中从txt文件中读取学生的信息。我写了一个Screen()类和StudentTable()类,其中Screen类有TabbedPane,有两个JPanel选项卡“PList”和“PChart”。我想将我的StudentTable类添加到我的PList JPanel中。因此,当我运行Screen类时,它将显示其中包含student表的StudentTable类。通常情况下,我设法显示我的表没有标签。 首先,我打开“Students.txt”文件,然后我读取了该文件。然后我关闭了文件。之后我创建了一个创建表的void方法createTable()。该表从ArrayList获取信息。现在,我想将此类添加到我的PList JPanel中。代码有点长。所以我上传了它们。但是,如果你想让我分享代码,我也可以这样做 的 Screen.java

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Screen extends JFrame implements ActionListener {
    private JTabbedPane tabbedPane;
    private JPanel PList, PChart;
    private JMenuBar menuBar;
    private JMenu menuStudent, menuSort, menuFilter;
    private JMenuItem addStudent, removeStudent, removeAllStudents;
    private JMenuItem sortLastName, sortId, sortAverage;
    private JMenuItem filterLetterGrade, removeFilter;

    private StudentTable studentTable;

    public Screen() {
        // TODO Auto-generated constructor stub
        tabbedPane = new JTabbedPane();
        menuBar = new JMenuBar();
        menuStudent = new JMenu();
        menuSort = new JMenu();
        menuFilter = new JMenu();
        addStudent = new JMenuItem();
        removeStudent = new JMenuItem();
        removeAllStudents = new JMenuItem();
        sortLastName = new JMenuItem();
        sortId = new JMenuItem();
        sortAverage = new JMenuItem();
        filterLetterGrade = new JMenuItem();
        removeFilter = new JMenuItem();     
        PList = new JPanel();
        PChart = new JPanel();

        studentTable = new StudentTable();

        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        setExtendedState(MAXIMIZED_BOTH);
        setTitle("Screen");
        setLayout(new BorderLayout());
        setJMenuBar(menuBar);

        // Menu
        menuStudent.setText("Student");
        addStudent.setText("Add Student");
        addStudent.addActionListener(this);
        removeStudent.setText("Remove Student");
        removeStudent.addActionListener(this);
        removeAllStudents.setText("Remove All Students");
        removeAllStudents.addActionListener(this);
        menuStudent.add(addStudent);
        menuStudent.add(removeStudent);
        menuStudent.add(removeAllStudents);

        menuSort.setText("Sort");
        sortLastName.setText("Sort by last name");
        sortLastName.addActionListener(this);
        sortId.setText("Sort by ID");
        sortId.addActionListener(this);
        sortAverage.setText("Sort by average");
        sortAverage.addActionListener(this);
        menuSort.add(sortLastName);
        menuSort.add(sortId);
        menuSort.add(sortAverage);

        menuFilter.setText("Filter");
        filterLetterGrade.setText("Filter by letter grade");
        filterLetterGrade.addActionListener(this);
        removeFilter.setText("Remove filter");
        removeFilter.addActionListener(this);
        menuFilter.add(filterLetterGrade);
        menuFilter.add(removeFilter);

        menuBar.add(menuStudent);
        menuBar.add(menuSort);
        menuBar.add(menuFilter);

        // Tabs
        tabbedPane.add("List", PList);
        tabbedPane.add("Chart", PChart);
        add(tabbedPane);
        PList.add(studentTable);

    }

    public static void main(String[] args) {
        new Screen();

    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}

StudentTable.java

import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

public class StudentTable extends JPanel {

    private static JTable table;
    private String name, lastName, letterGrade;
    private long studentId;
    private double quiz1,quiz2,project,midterm,finalGrade,average;
    private static ArrayList<Students> studentList;
    private Scanner scanner;

    public StudentTable() {
    }

    /**
     * 
     * @param name
     * @param lastName
     * @param studentId
     * @param quiz1
     * @param quiz2
     * @param project
     * @param midterm
     * @param finalGrade
     * @param average
     * @param letterGrade
     */
    public StudentTable(String name, String lastName, long studentId, double quiz1, double quiz2, double project, double midterm, double finalGrade, double average, String letterGrade) {
        this.name = name;
        this.lastName = lastName;
        this.letterGrade = letterGrade;
        this.studentId = studentId;
        this.quiz1 = quiz1;
        this.quiz2 = quiz2;
        this.project = project;
        this.midterm = midterm;
        this.finalGrade = finalGrade;
        this.average = average;
    }

    // GET & SET METHODS
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getLetterGrade() {
        return letterGrade;
    }
    public void setLetterGrade(String letterGrade) {
        this.letterGrade = letterGrade;
    }
    public long getStudentId() {
        return studentId;
    }
    public void setStudentId(long studentId) {
        this.studentId = studentId;
    }
    public double getQuiz1() {
        return quiz1;
    }
    public void setQuiz1(double quiz1) {
        this.quiz1 = quiz1;
    }
    public double getQuiz2() {
        return quiz2;
    }
    public void setQuiz2(double quiz2) {
        this.quiz2 = quiz2;
    }
    public double getProject() {
        return project;
    }
    public void setProject(double project) {
        this.project = project;
    }
    public double getMidterm() {
        return midterm;
    }
    public void setMidterm(double midterm) {
        this.midterm = midterm;
    }
    public double getFinalGrade() {
        return finalGrade;
    }
    public void setFinalGrade(double finalGrade) {
        this.finalGrade = finalGrade;
    }
    public double getAverage() {
        return average;
    }
    public void setAverage(double average) {
        this.average = average;
    }
    public ArrayList<Students> getStudentList() {
        return studentList;
    }
    public void setStudentList(ArrayList<Students> studentList) {
        this.studentList = studentList;
    }

    // Opening "Students.txt" file from a url.
    public void openFile() {
        try {
            URL url = new URL("http://rawsly.com/Students.txt");
            scanner = new Scanner(url.openStream());
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Reading "Students.txt" file and adding students to the "studentList" ArrayList.
    public void readFile() {
        studentList = new ArrayList<>();
        while(scanner.hasNext()) {
            name = scanner.next();
            lastName = scanner.next();
            studentId = scanner.nextLong();
            quiz1 = scanner.nextDouble();
            quiz2 = scanner.nextDouble();
            project = scanner.nextDouble();
            midterm = scanner.nextDouble();
            finalGrade = scanner.nextDouble();
            average = scanner.nextDouble();
            letterGrade = scanner.next();
            studentList.add(new Students(name, lastName, studentId, quiz1, quiz2, project, midterm, finalGrade, average, letterGrade));
        }
    }

    // Closing "Students.txt" file.
    public void closeFile() {
        scanner.close();
    }

    public void createTable() {
        openFile();
        readFile();
        closeFile();
        String [] columnNames = {"NAME", "SURNAME", "ID", "QUIZ1", "QUIZ2", "PROJECT", "MIDTERM", "FINAL", "AVERAGE", "LETTER GRADE"};
        Object [][] data = new Object[studentList.size()][10];
        for(int i=0; i<studentList.size(); i++) {
            for(int j=0; j<10; j++) {
                switch (j) {
                case 0:
                    data[i][0] = studentList.get(i).getName();
                    break;
                case 1:
                    data[i][1] = studentList.get(i).getLastName();
                    break;
                case 2:
                    data[i][2] = studentList.get(i).getStudentId();
                    break;
                case 3:
                    data[i][3] = studentList.get(i).getQuiz1();
                    break;
                case 4:
                    data[i][4] = studentList.get(i).getQuiz2();
                    break;
                case 5:
                    data[i][5] = studentList.get(i).getProject();
                    break;
                case 6:
                    data[i][6] = studentList.get(i).getMidterm();
                    break;
                case 7:
                    data[i][7] = studentList.get(i).getFinalGrade();
                    break;
                case 8:
                    data[i][8] = studentList.get(i).getAverage();
                    break;
                case 9:
                    data[i][9] = studentList.get(i).getLetterGrade();
                    break;
                } // end of the switch
            } // end of the first for loop
        } // end of the second for loop

        table = new JTable(data,columnNames) {
            public boolean isCellEditable(int row, int column) { // To make row and columns not editable
                return false;
            }
        };
        table.setFillsViewportHeight(true);
        table.setAutoCreateRowSorter(true); // to activate sorting property of each column
    }

    public static void main(String[] args) {
        StudentTable s = new StudentTable();
        s.createTable();
    }
}

1 个答案:

答案 0 :(得分:1)

这就是您在屏幕类中创建一个带有表格的面板的方式。

studentTable = new StudentTable();

这就是StudentTable的构造函数。

public StudentTable() {}

你在这看到问题了吗?你正在调用一个空的构造函数。

您可以尝试通过在表构造函数中实际创建表或通过在对象上显式调用createTable()来修复它。

所以要么在Screen做。

// Tabs
tabbedPane.add("List", PList);
tabbedPane.add("Chart", PChart);
add(tabbedPane);
studentTable.createTable(); // Create the table
PList.add(studentTable);
validate(); // Revalidate the frame

或者在StudentTable类中创建表。

public StudentTable() {
    createTable();
}

看,就这么简单。它现在有效吗?并不是的。 StudentTable是Panel,您实际上从未向其添加任何内容。因此,您只需在TabbedPane中添加一个空面板。

您需要在某些时候将表格实际添加到Panel。因此,请返回StudentTable类并在add(table)方法的末尾添加createTable()。或者如果你在构造函数中调用createTable(),你也可以在构造函数中添加这一行,在createTable()下面。

public StudentTable() {
    createTable();
    add(table);
}
你现在能看到一张桌子吗?是的你可以。你能看到表中的所有值吗?你不能。这是因为表格不可滚动。您需要将其添加到ScrollPane

最简单的方法是在ScrollPane班级中创建StudentTable。将Table添加到ScrollPane,然后将ScrollPane添加到Panel

返回到add(table)课程中StudentTable替换编写的位置。

JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
add(scrollPane);

现在应该解决你的问题。

另外,我想指出你使用太多的类字段。例如,在StudentTable班级中,namelastNameletterGradestudentIdquiz1quiz2,{{1 }},projectmidtermfinalGradeaverage无法用作字段。除了一个之外的所有都不是表的属性,它们不代表表的实例。它们代表scanner我建议您查看this answer相关问题。

  

您永远不应该使用字段来简化从一个方法到另一个方法的数据传递。这根本不是它的目的。这样做也会使您的方法本质上不安全或需要同步。

每个班级中也不需要Student方法。它只是在代码启动时作为代码的入口点,就是它。

关于getter和setter,只添加你需要的。你的main()类不会访问screen类中的任何字段(可以理解,因为大多数字段都不合理,对其他类完全没用),但是每个类都有一个getter和setter他们 如果你确实有很多getter和setter,最后把它们放在最后,这就不用滚动20分钟来访问类中的任何实际实现。

以下是我可能会编写StudentTable类的方法。

StudentTable