2014-07-10 2 views
0

배열이 People 인 경우를 가정 해 보겠습니다. 이 사람들은 이름, 직책, 직위, 급여와 같은 여러 분야를 가지고 있습니다.JTable을 객체로 채우는 가장 좋은 방법은 무엇입니까?

대부분의 질문은 JTable을 2 차원 배열로 채우는 것에 관한 것입니다. 제가 잘못하지 않는 한 정확하게하려고하는 것이 아닙니다.

버튼을 클릭하고 JTable 사람의 배열을보고 해당 테이블을 표시하고 싶습니다.

감사합니다.

편집 : 여기서 특정 값을 사용하여 업데이트하려면 setModel 인수를 변경할 수 있기를 바랍니다.

JButton btnRefresh = new JButton("Refresh"); 
    btnRefresh.addMouseListener(new MouseAdapter() { 
     @Override 
     public void mouseClicked(MouseEvent arg0) { 
      table_1.setModel(new DefaultTableModel(new Object[][] {}, new String[] { 
        "#", "Song", "Artist", "Time" })); 
      table_1.getColumnModel().getColumn(0).setPreferredWidth(22); 
      table_1.getColumnModel().getColumn(1).setPreferredWidth(191); 
      table_1.getColumnModel().getColumn(2).setPreferredWidth(179); 
      panel_3.revalidate(); 
     } 
    }); 

그래서 나는이 문자열 값을 변경하여 열 머리글을 변경할 수 있어요 그러나 나는 무엇 new Object[][]{}을 변경할 수 있습니까?

+3

JTable 자습서, 특히 AbstractTableModel을 확장하여 자체 테이블 모델을 정의하는 부분을 읽으십시오. http://docs.oracle.com/javase/tutorial/uiswing/components/table.html –

+0

몇 시간 전에 설명서를 보았지만 조금 복잡해 보였습니다. 그게 내가보기에 가장 쉬운 방법이라면, 나는 방금 쓴 편집과 관련된 것을 사용하고 싶다. –

+2

버튼 클릭에 반응하기 위해 마우스 리스너를 사용하지 마십시오. 키보드로 버튼을 클릭 할 수 있습니다. ActionListener를 사용하십시오. AbstractListener의 서브 클래스를 정의하는 것은 전혀 어렵지 않습니다. 하지만 너는 노력해야 해. –

답변

0

이 코드 조각은 내가 필요로하는 것과 정확히 동일합니다.

JButton btnRefresh = new JButton("Refresh"); 
     btnRefresh.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseClicked(MouseEvent arg0) { 
       table.setModel(new DefaultTableModel(dataArray(), 
         new String[] { "first", "second", "third", "fourth" }));//Changes the column headers 
       panel.revalidate(); 
      } 
      private Object[][] dataArray() { 
       Object[][] table = new Object[5][4];//5 = rows 4 = columns 
       for (int i = 0; i < 5; i++) { 
        for(int j = 0; j< 4; j++){     
          if(j == 0){ 
           table[i][j] = i+1; 
          }else if(j== 1){ 
           table[i][j] = "Second Row";//Change these strings to whatever variable you want to fill the second row with, same with the other 3. 
          }else if(j== 2){ 
           table[i][j] = "Third Row"; 
          }else{ 
           table[i][j] = "Fourth Row"; 
          } 
         } 
        } 
       return table; 
      } 
     }); 
+1

버튼에 MouseListener를 추가하는 이유는 무엇입니까? ActionListener를 사용해야합니다. –

관련 문제