Java Swing 表格组件


Swing 表格组件

  • 表格也是 GUI 中常用的组件,它是一个由多行、多列组成的二维显示区。Swing 的 JTable 以及相关类提供了对表格的支持。使用 JTable 以及相关类,可以创建功能丰富的表格,还可以为表格定义各种显示外观和编辑特性;

1. 创建表格

  • 在 JTable 类中除了默认的构造方法外,还提供了利用指定表格列名数组和表格数据数组创建表格的构造方法,代码如下:JTable(Object[][] rowData, Object[] columnNames),其中 rowData 是封装表格数据的数组,columnNames 是封装表格列名的数组;
  • 在使用表格时,通常将其添加到滚动面板中,然后将滚动面板添加到相应的位置;

a. 应用:可以滚动的表格

import javax.swing.*;
import java.awt.*;

public class Test extends JFrame {
    public static void main(String args[]) {
        Test frame = new Test();
        frame.setVisible(true);
    }

    public Test() {
        super();
        setTitle("Regino");
        setBounds(100, 100, 240, 150);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String[] columnNames = {"A", "B"}; // 定义表格列名数组
        // 定义表格数据数组
        String[][] tableValues = {{"A1", "B1"}, {"A2", "B2"},
                {"A3", "B3"}, {"A4", "B4"}, {"A5", "B5"}};
        // 创建指定列名和数据的表格
        JTable table = new JTable(tableValues, columnNames);
        // 创建显示表格的滚动面板
        JScrollPane scrollPane = new JScrollPane(table);
        // 将滚动面板添加到边界布局的中间
        getContentPane().add(scrollPane, BorderLayout.CENTER);
    }
}
  • 效果图:
    11

b. 应用:定义表格

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import java.awt.*;
import java.util.Vector;

public class Test extends JFrame {
    public static void main(String args[]) {
        Test frame = new Test();
        frame.setVisible(true);
    }
    public Test() {
        super();
        setTitle("Regino");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        String[] columnNames = { "A", "B", "C", "D", "E", "F", "G" };
        Vector columnNameV = new Vector();
        for (int column = 0; column < columnNames.length; column++) {
            columnNameV.add(columnNames[column]);
        }
        Vector tableValueV = new Vector();
        for (int row = 1; row < 21; row++) {
            Vector rowV = new Vector();
            for (int column = 0; column < columnNames.length; column++) {
                rowV.add(columnNames[column] + row);
            }
            tableValueV.add(rowV);
        }
        JTable table = new MTable(tableValueV, columnNameV);
        // 关闭表格列的自动调整功能
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        // 选择模式为单选
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        // 被选择行的背景色为黄色
        table.setSelectionBackground(Color.YELLOW);
        // 被选择行的前景色(文字颜色)为红色
        table.setSelectionForeground(Color.RED);
        table.setRowHeight(30); // 表格的行高为30像素
        scrollPane.setViewportView(table);
    }
    private class MTable extends JTable { // 实现自己的表格类
        public MTable(Vector rowData, Vector columnNames) {
            super(rowData, columnNames);
        }
        @Override
        public JTableHeader getTableHeader() { // 定义表格头
            // 获得表格头对象
            JTableHeader tableHeader = super.getTableHeader();
            tableHeader.setReorderingAllowed(false); // 设置表格列不可重排
            DefaultTableCellRenderer hr = (DefaultTableCellRenderer) tableHeader
                    .getDefaultRenderer(); // 获得表格头的单元格对象
            // 设置列名居中显示
            hr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
            return tableHeader;
        }
        // 定义单元格
        @Override
        public TableCellRenderer getDefaultRenderer(Class<?> columnClass) {
            DefaultTableCellRenderer cr = (DefaultTableCellRenderer) super
                    .getDefaultRenderer(columnClass); // 获得表格的单元格对象
            // 设置单元格内容居中显示
            cr.setHorizontalAlignment(DefaultTableCellRenderer.CENTER);
            return cr;
        }
        @Override
        public boolean isCellEditable(int row, int column) { // 表格不可编辑
            return false;
        }
    }
}
  • 效果图:
    12

2. 操作表格

  • 在编写应用表格的程序时,经常需要获得表格的一些信息,如表格的行数和列数。下面是 JTable 类中 3 个经常用来获得表格信息的方法:getRowCount():获得表格的行数,返回值为 int 型;getColumnCount():获得表格的列数,返回值为 int 型;getColumnName(int column):获得位于指定索引位置的列的名称,返回值为 String 型;

a. 应用:操作表格

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

public class Test extends JFrame {
    private JTable table;
    public static void main(String args[]) {
        Test frame = new Test();
        frame.setVisible(true);
    }
    public Test() {
        super();
        setTitle("Regino");
        setBounds(100, 100, 500, 375);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        final JScrollPane scrollPane = new JScrollPane();
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        String[] columnNames = { "A", "B", "C", "D", "E", "F", "G" };
        Vector columnNameV = new Vector();
        for (int column = 0; column < columnNames.length; column++) {
            columnNameV.add(columnNames[column]);
        }
        Vector tableValueV = new Vector();
        for (int row = 1; row < 21; row++) {
            Vector rowV = new Vector();
            for (int column = 0; column < columnNames.length; column++) {
                rowV.add(columnNames[column] + row);
            }
            tableValueV.add(rowV);
        }
        table = new JTable(tableValueV, columnNameV);
        table.setRowSelectionInterval(1, 3);// 设置选中行
        table.addRowSelectionInterval(5, 5);// 添加选中行
        scrollPane.setViewportView(table);

        JPanel buttonPanel = new JPanel();
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        JButton selectAllButton = new JButton("全部选择");
        selectAllButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.selectAll();// 选中所有行
            }
        });
        buttonPanel.add(selectAllButton);

        JButton clearSelectionButton = new JButton("取消选择");
        clearSelectionButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                table.clearSelection();// 取消所有选中行的选择状态
            }
        });
        buttonPanel.add(clearSelectionButton);
        //
        System.out.println("表格共有" + table.getRowCount() + "行"
                + table.getColumnCount() + "列");
        System.out.println("共有" + table.getSelectedRowCount() + "行被选中");
        System.out.println("第3行的选择状态为:" + table.isRowSelected(2));
        System.out.println("第5行的选择状态为:" + table.isRowSelected(4));
        System.out.println("被选中的第一行的索引是:" + table.getSelectedRow());
        int[] selectedRows = table.getSelectedRows();// 获得所有被选中行的索引
        System.out.print("所有被选中行的索引是:");
        for (int row = 0; row < selectedRows.length; row++) {
            System.out.print(selectedRows[row] + "  ");
        }
        System.out.println();
        System.out.println("列移动前第2列的名称是:" + table.getColumnName(1));
        System.out.println("列移动前第2行第2列的值是:" + table.getValueAt(1, 1));
        table.moveColumn(1, 5);// 将位于索引1的列移动到索引5处
        System.out.println("列移动后第2列的名称是:" + table.getColumnName(1));
        System.out.println("列移动后第2行第2列的值是:" + table.getValueAt(1, 1));
    }
}
  • 效果图:
    21
  • 对应输出:
    22
发布了269 篇原创文章 · 获赞 270 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Regino/article/details/104909125