2017-11-18 14 views
0

나는 학생들을위한 정보가 txt 파일에서 읽혀지는 800 명의 학생들의 테이블을 보여주는 GUI를 쓰고있다. Screen 클래스에 두 개의 JPanel 탭 "PList"와 "PChart"가있는 TabbedPane이있는 Screen 클래스와 StudentTable() 클래스를 작성했습니다. 내 PList JPanel에 StudentTable 클래스를 추가하고 싶습니다. 그래서 Screen 클래스를 실행하면 students 테이블이있는 StudentTable 클래스가 표시됩니다. 일반적으로 나는 탭없이 테이블을 보여 주었다. 먼저 "Students.txt"파일을 연 다음 파일을 읽었습니다. 그런 다음 파일을 닫았습니다. 그 후 테이블을 생성하는 void 메소드 createTable()을 생성했습니다. 테이블은 ArrayList에서 정보를 가져옵니다. 이제이 클래스를 내 PList JPanel에 추가하려고합니다. 코드는 좀 길다. 그래서 나는 그들을 업로드했다. 그러나 내가 코드를 공유하기를 원한다면, 나는 그것을 할 수있다. 화면 클래스의 표와 패널을 만드는 방법
Screen.javaJTable을 JTabbedPane에 추가하는 방법?

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

질문에 코드를 게시하십시오. 두 번째로, 생성 된'JTable'을 사용하지 않았으니 최소한'StudentTable'에 getter를 추가하여'Screen'에서'JTable'을 얻고 적절한 패널에'JTable'을 추가하십시오. 셋째, 코드를 두 번 다시 생각해보십시오. 여러 가지 나쁜 점이 있습니다. –

+0

좋아요, 다시 작업하겠습니다. 귀하의 제안에 감사드립니다. :) – rawsly

+0

당신이'PList.add (studentTable);'에 의해 테이블을 추가하는 것을 봅니다. 문제가 정확히 무엇입니까? – c0der

답변

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에 추가하는 것입니다.

실제로 어떤 시점에서 테이블을 패널에 추가해야합니다. 따라서 StudentTable 클래스로 돌아가 createTable() 메서드 끝에 add(table)을 추가하십시오. 또는 생성자에서 createTable()을 호출하는 경우 createTable() 아래의 생성자에서이 행을 추가 할 수도 있습니다.

public StudentTable() { 
    createTable(); 
    add(table); 
} 

테이블을 지금 볼 수 있습니까? 그래 넌 할수있어. 표의 모든 값을 볼 수 있습니까? 아니 당신은 할 수 없습니다. 테이블이 스크롤 할 수 없기 때문입니다. ScrollPane에 추가해야합니다.

가장 쉬운 방법은 StudentTable 클래스에 ScrollPane을 만드는 것입니다. ScrollPaneTable을 추가 한 다음 을 Panel에 추가하십시오.

StudentTable 클래스에 add(table)을 작성한 곳으로 돌아가서 으로 바꿉니다.

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

이제 문제가 해결 될 것입니다.

추가로, 나는 당신이 너무 많은 클래스 필드를 사용한다는 것을 지적하고 싶다. StudentTable 클래스, name, lastName, letterGrade, studentId, quiz1, quiz2, project, midterm, 예를 들어 finalGrade, averagescanner는 필드 인 아무 소용이 없습니다. 하나만 제외하고는 모두 테이블의 속성이 아니며 테이블의 인스턴스를 나타내지는 않습니다. 그들은 Student을 대표합니다. 관련 질문에 this answer을 살펴 보시기 바랍니다.

한 방법에서 다른 방법으로 데이터를 쉽게 전달하기 위해 필드를 사용하지 마십시오. 그것은 그 목적이 아닙니다. 이렇게하면 메서드가 본질적으로 안전하지 않거나 동기화가 필요하게됩니다.

각 클래스마다 main() 메서드가 필요하지 않습니다. 코드가 시작될 때 엔트리 포인트 역할을합니다.

getters 및 setter에 관해서는 필요한 항목 만 추가하십시오. screen 클래스는 StudentTable 클래스의 필드에 액세스하지 않습니다. (대부분 이해할 수 없으므로 다른 클래스에서는 완전히 쓸모가 없으므로 이해할 수있을 것입니다.) 그렇지만 그 중 하나 하나마다 getter와 setter가 있습니다. getter와 setter가 많으면 마지막에 넣으십시오. 그러면 클래스의 실제 구현에 액세스하기 위해 20 분 스크롤하지 않아도됩니다.

다음은 내가 StudentTable 클래스를 작성한 방법입니다.

import java.io.IOException; 
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 StudentTablePanel extends JPanel { 

    private static JTable table; 

    public StudentTablePanel() { 
     table = createTable(getStudentList()); // This line—in my opinion—makes it more immediately understandable what is happening, you're creating a table from a list of students. 
     JScrollPane scrollPane = new JScrollPane(table); 
     table.setFillsViewportHeight(true); 
     add(scrollPane); 
    } 

    // Reading "Students.txt" file and adding students to the "studentList" ArrayList. 
    public ArrayList<Students> getStudentList() { 
     ArrayList<Students> list = new ArrayList<>(); 
     try (Scanner scanner = new Scanner(new URL("http://rawsly.com/Students.txt").openStream())) { // Try with resources loop automatically closes the scanner when done 
      while (scanner.hasNext()) { 
       String name = scanner.next(); 
       String lastName = scanner.next(); 
       long studentId = scanner.nextLong(); 
       double quiz1 = scanner.nextDouble(); 
       double quiz2 = scanner.nextDouble(); 
       double project = scanner.nextDouble(); 
       double midterm = scanner.nextDouble(); 
       double finalGrade = scanner.nextDouble(); 
       double average = scanner.nextDouble(); 
       String letterGrade = scanner.next(); 
       list.add(new Students(name, lastName, studentId, quiz1, quiz2, project, midterm, finalGrade, average, letterGrade)); 
      } 
     } catch (IOException ex) { 
      // Handle your exception 
     } 
     return list; 
    } 

    public JTable createTable(ArrayList<Students> studentList) { 
     String[] columnNames = {"NAME", "SURNAME", "ID", "QUIZ1", "QUIZ2", "PROJECT", "MIDTERM", "FINAL", "AVERAGE", "LETTER GRADE"}; 
     int row = studentList.size(); 
     int column = columnNames.length; 
     Object[][] data = new Object[row][column]; 
     for (int i = 0; i < row; i++) { 
      for (int j = 0; j < column; 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(); 
       } // end of the switch 
      } // end of the first for loop 
     } // end of the second for loop 

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

     return newTable; 
    } 
} 
+0

당신은 훌륭합니다! 귀하의 의견에 진심으로 감사드립니다! 나는 당신의 설명을 매우 조심스럽게 공부할 것입니다. – rawsly