📜  Java Swing-JTable

📅  最后修改于: 2020-09-30 05:56:51             🧑  作者: Mango

Java JTable

JTable类用于以表格形式显示数据。它由行和列组成。

JTable类声明

我们来看一下javax.swing.JTable类的声明。

常用的构造函数:

Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

Java JTable示例

import javax.swing.*;  
public class TableExample {  
    JFrame f;  
    TableExample(){  
    f=new JFrame();  
    String data[][]={ {"101","Amit","670000"},  
                          {"102","Jai","780000"},  
                          {"101","Sachin","700000"}};  
    String column[]={"ID","NAME","SALARY"};       
    JTable jt=new JTable(data,column);  
    jt.setBounds(30,40,200,300);        
    JScrollPane sp=new JScrollPane(jt);  
    f.add(sp);        
    f.setSize(300,400);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new TableExample();  
}  
}

输出:

具有ListSelectionListener的Java JTable示例

import javax.swing.*;  
import javax.swing.event.*;
public class TableExample {  
  public static void main(String[] a) {
    JFrame f = new JFrame("Table Example");
    String data[][]={ {"101","Amit","670000"},  
                                                                       {"102","Jai","780000"},  
                                                                       {"101","Sachin","700000"}};  
                            String column[]={"ID","NAME","SALARY"};       
                            final JTable jt=new JTable(data,column);  
    jt.setCellSelectionEnabled(true);
    ListSelectionModel select= jt.getSelectionModel();
    select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    select.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        String Data = null;
        int[] row = jt.getSelectedRows();
        int[] columns = jt.getSelectedColumns();
        for (int i = 0; i < row.length; i++) {
          for (int j = 0; j < columns.length; j++) {
            Data = (String) jt.getValueAt(row[i], columns[j]);
          } }
        System.out.println("Table element selected is: " + Data);  
      }     
    });
    JScrollPane sp=new JScrollPane(jt);  
    f.add(sp);
    f.setSize(300, 200);
    f.setVisible(true);
  }
}

输出:

如果在“名称”列中选择一个元素,则该元素的名称将显示在控制台上:

Table element selected is: Sachin