流程

查看代码注解

实现

代码

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

public class JtableTest extends JFrame{
public JtableTest() {
	Container c=this.getContentPane();
		
	//声明表数据data
	Vector<Vector<Object>> data=new Vector<Vector<Object>>();
		
	//添加第一行表数据
	Vector<Object> v1=new Vector<Object>();
	v1.add("马云");
	v1.add("34");
	data.add(v1);
		
	//添加第二行表数据
	Vector<Object> v2=new Vector<Object>();
	v2.add("王健林");
	v2.add("40");
	data.add(v2);
		
	//声明表头olumnName
	Vector<String> columnName=new Vector<String>();
	columnName.add("姓名");
	columnName.add("年龄");
		
	//创建dtm
	final DefaultTableModel dtm=new DefaultTableModel(data,columnName);
	JTable jtable=new JTable(dtm);
	c.add(new JScrollPane(jtable));
		
	//用于逻辑层收集数据
	JPanel jpl=new JPanel();
	JLabel jlbName=new JLabel("姓名");
	jpl.add(jlbName);
	final JTextField tfdName=new JTextField(10);
	jpl.add(tfdName);
	JLabel jlbAge=new JLabel("年龄");
	jpl.add(jlbAge);
	final JTextField tfdAge=new JTextField(10);
	jpl.add(tfdAge);
		
	//逻辑层
	JButton btnadd=new JButton("添加");
	jpl.add(btnadd);
	btnadd.addActionListener(new ActionListener() {

		@Override
		public void actionPerformed(ActionEvent e) {
			//收集数据
			String name=tfdName.getText();
			String age=tfdAge.getText();
			//将收集好的数据封装为一行
			Vector<Object> rowData=new Vector<Object>();
			rowData.add(name);
			rowData.add(age);
			//添加到整个dtm中
			dtm.addRow(rowData);			
		}
	});
	JLabel jlbel=new JLabel("请选择你要删除的行,然后点击删除:");
	jpl.add(jlbel);
	JButton btndel=new JButton("删除");
	jpl.add(btndel);
	btndel.addActionListener(new ActionListener() {
   			@Override
			public void actionPerformed(ActionEvent e) {
			//得到选择行号
			int name=jtable.getSelectedRow();
			//dtm执行删除
			dtm.removeRow(name);
		}
	});
	c.add(jpl,BorderLayout.SOUTH);
	this.setTitle("用户添加/删除");
	this.setBounds(100,200,800,300);
	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	this.setVisible(true);
}
public static void main(String[] args) {
	new JtableTest();

}
}