zoukankan      html  css  js  c++  java
  • JTable使用

    The JTable is used to display and edit regular two-dimensional tables of cells. See How to Use Tables in The Java Tutorial for task-oriented documentation and examples of using JTable.

    The JTable has many facilities that make it possible to customize its rendering and editing but provides defaults for these features so that simple tables can be set up easily. For example, to set up a table with 10 rows and 10 columns of numbers:

    The table in SimpleTableDemo.java declares the column names in a String array:

    String[] columnNames = {"First Name",
                            "Last Name",
                            "Sport",
                            "# of Years",
                            "Vegetarian"};
    

    Its data is initialized and stored in a two-dimensional Object array:

    Object[][] data = {
        {"Kathy", "Smith",
         "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe",
         "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black",
         "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White",
         "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown",
         "Pool", new Integer(10), new Boolean(false)}
    };
    

    Then the Table is constructed using these data and columnNames:

    JTable table = new JTable(data, columnNames);
    

    There are two JTable constructors that directly accept data (SimpleTableDemo uses the first):

    • JTable(Object[][] rowData, Object[] columnNames)
    • JTable(Vector rowData, Vector columnNames)

    The advantage of these constructors is that they are easy to use. However, these constructors also have disadvantages:

    • They automatically make every cell editable.
    • They treat all data types the same (as strings). For example, if a table column has Boolean data, the table can display the data in a check box. However, if you use either of the two JTable constructors listed previously, your Boolean data is displayed as a string. You can see this difference in the Vegetarian column of the previous figure.
    • They require that you put all of the table's data in an array or vector, which may not be appropriate for some data. For example, if you are instantiating a set of objects from a database, you might want to query the objects directly for their values, rather than copying all their values into an array or vector.

    If you want to get around these restrictions, you need to implement your own table model, as described in Creating a Table Model.

    Adding a Table to a Container

    Here is typical code for creating a scroll pane that serves as a container for a table:

    JScrollPane scrollPane = new JScrollPane(table);
    table.setFillsViewportHeight(true); 不加这句,当容器整个高度小于数据table的高度时,会只显示部分数据,要想显示全部,必须要把容器拉大,加了这句,就会显示一个滚动条,可以上下滚动,当拉大容器足够显示后会消失。
    

    The two lines in this snippet do the following:

    • The JScrollPane constructor is invoked with an argument that refers to the table object. This creates a scroll pane as a container for the table; the table is automatically added to the container.
    • JTable.setFillsViewportHeight is invoked to set the fillsViewportHeight property. When this property is true the table uses the entire height of the container, even if the table doesn't have enough rows to use the whole vertical space. This makes it easier to use the table as a drag-and-drop target.

    The scroll pane automatically places the table header at the top of the viewport. The column names remain visible at the top of the viewing area when the table data is scrolled.

    If you are using a table without a scroll pane, then you must get the table header component and place it yourself. For example:

    container.setLayout(new BorderLayout());
    container.add(table.getTableHeader(), BorderLayout.PAGE_START);
    container.add(table, BorderLayout.CENTER);

    Setting and Changing Column Widths

    By default, all columns in a table start out with equal width, and the columns automatically fill the entire width of the table. When the table becomes wider or narrower (which might happen when the user resizes the window containing the table), all the column widths change appropriately.

    When the user resizes a column by dragging its right border, then either other columns must change size, or the table's size must change. By default, the table's size remains the same, and all columns to the right of the drag point resize to accommodate space added to or removed from the column to the left of the drag point.

    To customize initial column widths, you can invoke setPreferredWidth on each of your table's columns. This sets both the preferred widths of the columns and their approximate relative widths. For example, adding the following code to SimpleTableDemo makes its third column bigger than the other columns:

    TableColumn column = null;
    for (int i = 0; i < 5; i++) {
        column = table.getColumnModel().getColumn(i);
        if (i == 2) {
            column.setPreferredWidth(100); //third column is bigger
        } else {
            column.setPreferredWidth(50);
        }
    }
    利用TableColumn类所提供的setPreferredWidth()方法来设置字段宽度

    TableColumnModel getColumnModel()
    Returns the TableColumnModel that contains all column information of this table.

    public interface TableColumnModel

    Defines the requirements for a table column model object suitable for use with JTable.

    TableColumnModel的getColumn方法。

    TableColumn getColumn(int columnIndex)
    Returns the TableColumn object for the column at columnIndex.
    Parameters:
    columnIndex - the index of the desired column
    Returns:
    the TableColumn object for the column at columnIndex。

    另一篇:
    javax.swing.JComponent
    --javax.swing.JTabel
    在使用JTable以前,我们先看一下它的构造函数有哪些, 以及应该如何使用:

    JTabel构造函数:
    JTable():建立一个新的JTables,并使用系统默认的Model.
    JTable(int numRows,int numColumns):建立一个具有numRows行,numColumns列的空表格,使用的是DefaultTableModel.
    JTable(Object[][] rowData,Object[][] columnNames):建立一个显示二维数组数据的表格,且可以显示列的名称。
    JTable(TableModel dm):建立一个JTable,有默认的字段模式以及选择模式,并设置数据模式。
    JTable(TableModel dm,TableColumnModel cm):建立一个JTable,设置数据模式与字段模式,并有默认的选择模式。
    JTable(TableModel dm,TableColumnModel cm,ListSelectionModel sm):建立一个JTable,设置数据模式、字段模式、与选择模式。
    JTable(Vector rowData,Vector columnNames):建立一个以Vector为输入来源的数据表格,可显示行的名称。


    另外:

    javax.swing.JComponent
    --javax.swing.JTabel
    在使用JTable以前,我们先看一下它的构造函数有哪些, 以及应该如何使用:

    JTabel构造函数:
    JTable():建立一个新的JTables,并使用系统默认的Model.
    JTable(int numRows,int numColumns):建立一个具有numRows行,numColumns列的空表格,使用的是DefaultTableModel.
    JTable(Object[][] rowData,Object[] columnNames):建立一个显示二维数组数据的表格,且可以显示列的名称。
    JTable(TableModel dm):建立一个JTable,有默认的字段模式以及选择模式,并设置数据模式。
    JTable(TableModel dm,TableColumnModel cm):建立一个JTable,设置数据模式与字段模式,并有默认的选择模式。
    JTable(TableModel dm,TableColumnModel cm,ListSelectionModel sm):建立一个JTable,设置数据模式、字段模式、与选择模式。
    JTable(Vector rowData,Vector columnNames):建立一个以Vector为输入来源的数据表格,可显示行的名称。

    package JTable;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    
    public class SimpleTable {
        public SimpleTable()
        {
            JFrame f=new JFrame("test");
            Object[][] playerInfo={
                    {"阿呆",new Integer(66),new Integer(32),new Integer(98),new Boolean(false)},
                    {"阿呆",new Integer(82),new Integer(69),new Integer(128),new Boolean(true)}
            };
            
            String[] names={"1","2","3","4","5"};
            
            JTable table=new JTable(playerInfo,names);
            
            table.setPreferredScrollableViewportSize(new Dimension(550,30));
            JScrollPane scrollPane=new JScrollPane(table);
            f.getContentPane().add(scrollPane,BorderLayout.CENTER);
            f.setVisible(true);
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
            f.setSize(500,400);
    
        }
        public static void main(String[] args)
        {
            new SimpleTable();
        }
    
    }
    setPreferredScrollableViewportSize

    Sets the preferred size of the viewport for this table.

    Interface Scrollable

    An interface that provides information to a scrolling container like JScrollPane. A complex component that's likely to be used as a viewing a JScrollPane viewport (or other scrolling container) should implement this interface.

    JTable实现了这个接口。

     

  • 相关阅读:
    Json2JsonArray JsonArray2StringArray
    循环结构
    类型转换代码
    字符串的截取拼接
    循环语句,选择结构的相关代码
    Java代码2-运算符简单运用
    Java代码1
    集合框架
    接口
    继承多态
  • 原文地址:https://www.cnblogs.com/youxin/p/2791699.html
Copyright © 2011-2022 走看看