swing【最后一弹】JTable仿写简单Excel!
历时五天终于把所有的常用swing界面组件过了一遍,很多细节还需日后加深。愈发体会熟练查阅jdk文档的重要性,java各种类和方法太繁琐根本记不住,只能靠熟练的文档粘贴,用Eclipse会好很多。
源代码:
//source code import java.awt.BorderLayout ; import java.awt.event.ActionListener ; import java.awt.event.ActionEvent ; import java.awt.event.WindowListener ; import java.awt.event.WindowAdapter ; import java.awt.event.WindowEvent ; import javax.swing.JFrame ; import javax.swing.JButton ; import javax.swing.JTable ; import javax.swing.JPanel ; import javax.swing.JScrollPane ; import javax.swing.table.DefaultTableModel ; import javax.swing.table.TableColumn ; import javax.swing.table.TableColumnModel ; class MyAction implements ActionListener { private JFrame frame = new JFrame("通讯录表格") ; private JPanel panel = new JPanel() ; private DefaultTableModel tableModel ; private JTable table = null ; //声明表格 private JButton addColumn = new JButton("增加列") ; private JButton removeColumn = new JButton("移除列") ; private JButton addRow = new JButton("增加行") ; private JButton removeRow = new JButton("移除行") ; private String title[] = {"姓名","性别","年龄","手机号码","QQ号"} ; private Object person[][] = {{"王呆萌","男","20","18249778269","653866417"}, {"老王","男","44","18766324287","null"}} ; public MyAction() { this.frame.setLayout(new BorderLayout()) ; this.tableModel = new DefaultTableModel(this.person,this.title) ; //实例化tableModel table = new JTable(this.tableModel) ; JScrollPane scr = new JScrollPane(this.table) ; panel.add(this.addColumn) ; panel .add(this.addRow) ; panel.add(this.removeColumn) ; panel.add(this.removeRow) ; this.frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(1) ; } }) ; this.addColumn.addActionListener(this) ; this.addRow.addActionListener(this) ; this.removeColumn.addActionListener(this) ; this.removeRow.addActionListener(this) ; this.frame.add(this.panel,BorderLayout.NORTH) ; this.frame.add(scr,BorderLayout.CENTER) ; this.frame.setSize(400,250) ; this.frame.setVisible(true) ; } public void actionPerformed(ActionEvent e) { if(e.getSource() == addRow) { this.tableModel.addRow(new Object[]{}) ; } if(e.getSource() == addColumn) { this.tableModel.addColumn("新增列") ; } if(e.getSource() == removeRow) { int rowCount = this.tableModel.getRowCount()-1 ; if(rowCount >= 0) //判断是否还有行可删除 { this.tableModel.removeRow(rowCount) ; this.tableModel.setRowCount(rowCount) ; } } if(e.getSource() == removeColumn) { int columnCount = this.tableModel.getColumnCount()-1 ; if(columnCount>=0) { TableColumnModel model = this.table.getColumnModel() ; TableColumn tableColumn = model.getColumn(columnCount) ; model.removeColumn(tableColumn) ; this.tableModel.setColumnCount(columnCount) ; } else System.out.println("已无列可被删除!!!") ; } } }; class Tester { public static void main(String args[]) { new MyAction() ; } } ;