2012-08-25 5 views
2

JTable에서 검색 할 값을 입력 할 텍스트 필드를 제공하고이 입력 된 값이 JTable의 셀 값 중 하나와 일치하는 경우 JTable과 함께 기능을 갖길 원합니다. 해당 셀을 강조 표시해야합니다. & 셀 글꼴을 굵게 표시해야합니다. 텍스트 필드에 값을 지정한 후 사용자가 Enter 키를 누르면 값이 일치합니다.JTable에서 검색을 구현하는 방법

어떻게하면됩니까?

+3

위대한! 그래서 [무엇을 시도 했습니까?] (http://mattgemmell.com/2008/12/08/what-have-you-tried/) 그리고 어떤 문제가 있습니까? –

+0

나는 아무것도 시도하지 않았다. 단지 그것을 할 수있는 간단한 방법이 있는지 알고 싶다. – aoulhent

+1

예, 대부분이 [JTable 자습서] (http://docs.oracle.com/javase/tutorial/uiswing/components/table.html)에서 잘 설명됩니다. 너 아직 그들을 겪었 니? –

답변

15

이렇게하면 문제를 해결할 수 있습니다. 다음은 코드입니다.

public class JTableSearchAndHighlight extends JFrame { 

    private JTextField searchField; 
    private JTable table; 
    private JPanel panel; 
    private JScrollPane scroll; 

    public JTableSearchAndHighlight() { 

    initializeInventory(); 
    } 

private void initializeInventory() { 

    panel = new JPanel(); 

    searchField = new JTextField(); 

    panel.setLayout(null); 

    final String[] columnNames = {"Name", "Surname", "Age"}; 

    final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}, 
          {"Max", "Dumbass", "10"}, {"Melanie", "Martin", "500"}, 
          {"Jollibe", "Mcdonalds", "15"}}; 

    table = new JTable(data, columnNames); 
    table.setColumnSelectionAllowed(true); 
    table.setRowSelectionAllowed(true); 

    scroll = new JScrollPane(table); 
    scroll.setBounds(0, 200, 900, 150); 

    searchField.setBounds(10, 100, 150, 20); 
    searchField.addActionListener(new ActionListener() { 

     public void actionPerformed(ActionEvent e) { 

      String value = searchField.getText(); 

      for (int row = 0; row <= table.getRowCount() - 1; row++) { 

       for (int col = 0; col <= table.getColumnCount() - 1; col++) { 

        if (value.equals(table.getValueAt(row, col))) { 

         // this will automatically set the view of the scroll in the location of the value 
         table.scrollRectToVisible(table.getCellRect(row, 0, true)); 

         // this will automatically set the focus of the searched/selected row/value 
         table.setRowSelectionInterval(row, row); 

         for (int i = 0; i <= table.getColumnCount() - 1; i++) { 

          table.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer()); 
         } 
        } 
       } 
      } 
     } 
    }); 

    panel.add(searchField); 
    panel.add(scroll); 

    getContentPane().add(panel); 

    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    setTitle("Inventory Window"); 
    setSize(900, 400); 
    setLocationRelativeTo(null); 
    setVisible(true); 
} 

private class HighlightRenderer extends DefaultTableCellRenderer { 

    @Override 
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { 

     // everything as usual 
     super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 

     // added behavior 
     if(row == table.getSelectedRow()) { 

      // this will customize that kind of border that will be use to highlight a row 
      setBorder(BorderFactory.createMatteBorder(2, 1, 2, 1, Color.BLACK)); 
     } 

     return this; 
    } 
} 

public static void main(String[] args) { 

    SwingUtilities.invokeLater(new Runnable() { 

     public void run() { 

      new JTableSearchAndHighlight(); 
     } 
    }); 
    } 
} 
7

SwingX 프로젝트의 JXTable에는 테이블 검색을위한 내장 된 지원이 있습니다 (Searchable 인터페이스 찾습니다). 또한이 Searchable 인터페이스를 사용하는 검색 필드를 신속하게 만들 수 있습니다 : JXSearchField 및/또는 JXSearchPanel.

올바르게 기억하면 대부분의 요구 사항을 충족합니다. 셀 내용을 굵게 만들기위한 사용자 지정 코드를 추가하기 만하면됩니다.

+1

누가 다운 투표를했는지 확실하지 않습니다. 그것을 무효화하기 위해 투표했습니다. 이것은 유효한 답변입니다 –

+0

@HovercraftFullOfEels 또한 왜 downvote에 대한 이유가 궁금합니다. downvoter 적어도 내 대답을 정정/개선 할 수 있도록 아래쪽 투표 이유를 언급에 표시하면 항상 좋은 – Robin

+0

그래. 100 % 동의하십시오. –

관련 문제