Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào chúng ta có thể sắp xếp một JTable trên một cột cụ thể trong Java?


A JTable là một lớp con của JComponent lớp để hiển thị cấu trúc dữ liệu phức tạp. Thành phần JTable có thể tuân theo mẫu thiết kế Model View Controller (MVC) để hiển thị dữ liệu trong các hàng và cột. JTable có thể tạo TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener, RowSorterListener các giao diện. Chúng tôi có thể sắp xếp một JTable trong một cột cụ thể bằng cách sử dụng phương thức setAutoCreateRowSorter () và đặt thành true của lớp JTable.

Ví dụ

import java.awt.*;
import javax.swing.*;
public final class JTableSorterTest extends JFrame {
   private JTable table;
   private JScrollPane scrollPane;
   public JTableSorterTest() {
      setTitle("JTableHeaderHide Test");
      String[] columnNames = {"Name", "Age", "City"};
      Object[][] data = {{"Raja", "35", "Hyderabad"}, {"Adithya", "25", "Chennai"}, {"Vineet", "23",       "Mumbai"}, {"Archana", "32", "Pune"}, {"Krishna", "30", "Kolkata"}};
      table = new JTable(data, columnNames);
      scrollPane= new JScrollPane(table);
      table.setAutoCreateRowSorter(true); // sorting of the rows on a particular column
      add(scrollPane, BorderLayout.CENTER);
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JTableSorterTest();
   }
}

Đầu ra

Làm thế nào chúng ta có thể sắp xếp một JTable trên một cột cụ thể trong Java?