import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
public class Main extends JFrame{
private JTable table;
public Main() {
super();
setTitle("操作表格");
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container c = getContentPane();
String[] columnNames = {"A" ,"B" ,"C","D","E","F","G"};//定义表格列
String[][] tableValues = new String[20][columnNames.length];//定义数组,用来存储表格数据
for(int i = 0 ; i <tableValues.length ; i ++) {
for(int j = 0 ; j <columnNames.length ; j ++) {
tableValues[i][j] = columnNames[j]+i;
}
}
//tableValues:封装表格数据的数组,columnNames:封装表格列名的数组
JTable table = new JTable(tableValues,columnNames);
JScrollPane sc= new JScrollPane(table);
c.add(sc,BorderLayout.CENTER);
table.setSelectionForeground(Color.RED);//设置前景色,字体颜色
table.setSelectionBackground(Color.YELLOW);//背景色
table.setRowHeight(30);//设置行高
/*
* ListSelectionModel.MULTIPLE_INTERVAL_SELECTION:随便选
* ListSelectionModel.SINGLE_INTERVAL_SELECTION:连选
* ListSelectionModel.SINGLE_SELECTION:单选
* */
table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);//选择模式
System.out.println("列数为:"+table.getColumnCount()+" " +"行数为:"+ table.getRowCount());
System.out.println("第二列的名称为: " + table.getColumnName(1));//参数是行的索引
System.out.println("第二列第二行的值为: " + table.getValueAt(1,1));
}
public static void main(String[] args) {
Main m = new Main();
m.setVisible(true);
}
}
运行结果: