高级组件——表格JTable

JTable(Object[][] rowData,Object[] columnNames)
                        表格数据              列名集合

setSelectionMode(int selectionMode) 设置选择模式
3种选择模式:
  ListSelectionModel.MULTIPLE_INTERVAL_SELECTION 随便选
  ListSelectionModel.SINGLE_INTERVAL_SELECTION 连选(相邻)
  ListSelectionModel.SINGLE_SELECTION 单选

表格属性与操作:
  table.setSelectionBackground(Color.YELLOW); 设置选中行的字体颜色
  table.setSelectionForeground(Color.RED); 设置选中行的背景色
  table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
  table.setRowHeight(20);//设定行高20像素
  table.getRowCount();//获取行数
  表格索引位置都是从0开始:
  table.getColumnName(0);//获取第一列的名称
  table.getValueAt(0,0);//获取1行1列的值

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

public class Demo extends JFrame {
    public Demo(){
        setTitle("操作表格");
        setBounds(100,100,300,150);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        Container c=getContentPane();

        String[] columnNames={"A","B","C"};//列名
        String[][] tableValues=new String[10][columnNames.length];//定义表格大小10*3

        for (int row=0;row<tableValues.length;row++){//添加表格内容
            for (int column=0;column<columnNames.length;column++){
                tableValues[row][column]=columnNames[column]+row;
            }
        }

        JTable table=new JTable(tableValues,columnNames);//表格对象,并指定内容
        JScrollPane scrollPane=new JScrollPane(table);//滚动面板
        c.add(scrollPane,BorderLayout.CENTER);

        table.setSelectionBackground(Color.YELLOW);//被选中行的背景色
        table.setSelectionForeground(Color.RED);//被选中行的字体颜色
        table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//随便选
        //table.setRowHeight(20);//行高20像素
        //table.getColumnName(0);//获取第一列的名称
        //table.getRowCount();//获取行数
        //table.getValueAt(0,0);//获取1行1列的值
    }

    public static void main(String[] args) {
        Demo frame=new Demo();
        frame.setVisible(true);
    }
}

猜你喜欢

转载自www.cnblogs.com/xixixing/p/9777746.html
今日推荐