Java-Swing组件,维护JTable model学习

Java-Swing组件,维护JTable model学习_第1张图片
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Demo extends JFrame{
private DefaultTableModel model;
private JTable table;
private JTextField t1,t2;
private JButton btn1,btn2,btn3;
public Demo() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setBounds(200, 200, 510, 420);
setTitle(“维护表格模型”);
Container c=getContentPane();
c.setLayout(null);
JPanel p1=new JPanel();
p1.setBounds(10, 10, 480, 280);
p1.setBorder(BorderFactory.createLineBorder(Color.black));
p1.setLayout(new BorderLayout());
JPanel p2=new JPanel();
p2.setBounds(10, 300, 480, 80);
p2.setBorder(BorderFactory.createLineBorder(Color.blue));
p2.setLayout(null);
String[] columnNames= {“A”,“B”};
String[][] tableValues= {{“A1”,“B1”},{“A2”,“B2”},{“A3”,“B3”}};
model=new DefaultTableModel(tableValues,columnNames);
table=new JTable(model);
table.setRowHeight(30);
JScrollPane sc=new JScrollPane(table);
p1.add(sc,BorderLayout.CENTER);

	t1=new JTextField();
	t1.setBounds(10, 10, 90, 60);
	t2=new JTextField();
	t2.setBounds(110, 10, 90, 60);
	btn1=new JButton("添加");
	btn1.setBounds(225, 10, 80, 60);
	btn2=new JButton("修改");
	btn2.setBounds(310, 10, 80, 60);
	btn3=new JButton("删除");
	btn3.setBounds(395, 10, 80, 60);
	p2.add(t1);
	p2.add(t2);
	p2.add(btn1);
	p2.add(btn2);
	p2.add(btn3);
	c.add(p1);
	c.add(p2);
	setVisible(true);
}
private void addListener() {
	btn1.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			String rowDate[]= {t1.getText(),t2.getText()};
			model.addRow(rowDate);
			int rowCount=table.getRowCount()+1;
			t1.setText("A"+rowCount);
			t2.setText("B"+rowCount);
		}
	});
	btn2.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			int selectedRow=table.getSelectedRow();
			if (selectedRow !=-1) {
				model.setValueAt(t1.getText(), selectedRow,0);
				model.setValueAt(t2.getText(), selectedRow,1);
			}
		}
	});
	btn3.addActionListener(new ActionListener() {
		@Override
		public void actionPerformed(ActionEvent e) {
			int selectedRow=table.getSelectedRow();
			if (selectedRow !=-1) {
				model.removeRow(selectedRow);
			}
		}
	});
}
public static void main(String[] args) {
	Demo d=new Demo();
	d.addListener();
}

}

你可能感兴趣的:(Java-Swing组件,维护JTable model学习)