work158.java
package test08;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
public class work158 extends JFrame
{
private JTable table1;
public work158()
{
this.setTitle("操纵表格");
final JScrollPane scrollPane1 = new JScrollPane();
this.getContentPane().add(scrollPane1,BorderLayout.CENTER);
String[] columns = {"A","B","C","D"};
String[][] tableValues = {{"A1","B1","C1","D1"},{"A2","B2","C2","D2"},{"A3","B3","C3","D3"},{"A4","B4","C4","D4"}};
table1 = new JTable(tableValues,columns);
table1.setRowSelectionInterval(0, 1);
table1.addRowSelectionInterval(3, 3);
scrollPane1.setViewportView(table1);
JPanel panel1 = new JPanel();
this.getContentPane().add(panel1,BorderLayout.SOUTH);
JButton buttonSelectAll = new JButton("全部选择");
buttonSelectAll.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
table1.selectAll();
}
});
panel1.add(buttonSelectAll);
JButton buttonClearSelect = new JButton("取消选择");
buttonClearSelect.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
table1.clearSelection();
}
});
panel1.add(buttonClearSelect);
System.out.println("表格共有" + table1.getRowCount() + "行");
System.out.println("表格共有" + table1.getColumnCount() + "列");
System.out.println("选中:" + table1.getSelectedRowCount() + "行");
System.out.println("第1行的状态为:" + table1.isRowSelected(0));
System.out.println("第3行的状态为:" + table1.isRowSelected(2));
System.out.println("被选中的首行索引是:" + table1.getSelectedRow());
int[] selectedRows = table1.getSelectedRows(); //获取被选中行
System.out.println("所有被选中的行索引是:");
for (int i = 0; i < selectedRows.length; i++)
{
System.out.print(" " + selectedRows[i]);
}
System.out.println();
System.out.println("移动前第1列的名称是:" + table1.getColumnName(0));
System.out.println("移动前第2行第1列的值是:" + table1.getValueAt(1, 0));
table1.moveColumn(0, 3);
System.out.println("移动后第1列的名称是:" + table1.getColumnName(0));
System.out.println("移动后第2行第1列的值是:" + table1.getValueAt(1, 0));
this.setSize(500,300);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
work158 s1 = new work158();
}
}