public class ExanpleFrame_04 extends JFrame{
private static final long serialVersionUID = 1L;
private JTable table ;
public ExanpleFrame_04() {
// TODO Auto-generated constructor stub
super();
setTitle("操控表格");
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<String> columnNameV = new Vector<>();
for(int i=0;i<columnNames.length;i++){
columnNameV.add(columnNames[i]);
}
Vector<Vector<String>> tableBalueV = new Vector<>();
for(int i=1;i<21;i++){
Vector<String>iV = new Vector<>();
for(int j=0;j<columnNames.length;j++){
iV.add(columnNames[j]+i);
}
tableBalueV.add(iV);
}
table = new JTable(tableBalueV,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() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
table.selectAll();
}
});
buttonpanel.add(selectALLButton);
JButton clearSelectionButton = new JButton("全部取消");
clearSelectionButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
table.clearSelection();
}
});
buttonpanel.add(clearSelectionButton);
System.out.println("表格共有" +table.getRowCount() + "行" + table.getColumnCount() + "列");
System.out.println("共有" + table.getSelectedColumnCount() +"行被选中");
System.out.println("第三行的选择状态为"+ table.isRowSelected(2));
System.out.println("第五行的选择状态为"+ table.isRowSelected(4));
System.out.println("被选中的第一行的引索是:" + table.getSelectedRow());
int[] selectedRows = table.getSelectedRows();
System.out.println("被选中所有行的引索是:");
for(int i=0;i<selectedRows.length;i++){
System.out.print(selectedRows[i] + " ");
}
System.out.println();
System.out.println("列移动前第二列的名称是:"+ table.getColumnName(1));
System.out.println("列移动前第二行第二列的值是:"+ table.getValueAt(1,1));
table.moveColumn(1, 5);
System.out.println("列移动后第二列的名称是" + table.getColumnName(1));
System.out.println("列移动前第二行第二列的值是:"+ table.getValueAt(1,1));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExanpleFrame_04 exanpleFrame_04 = new ExanpleFrame_04();
exanpleFrame_04.setVisible(true);
}
}