public class ToolTipList extends JFrame{
JTextField aTextField;
JTextField bTextField;
public ToolTipList(){//构造方法
JScrollPane scrollPane=new JScrollPane();
getContentPane().add(scrollPane, BorderLayout.CENTER);
String[] columnNames={"A","B"};
String[][] tableValues={{"A1","B1"},{"A2","B2"},{"A3","B3"}};
DefaultTableModel tableModel=new DefaultTableModel(tableValues, columnNames);
JTable table=new JTable(tableModel);
table.setRowSorter(new TableRowSorter(tableModel));//设置排序起
table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
int selectedRow=table.getSelectedRow();
Object oa=tableModel.getValueAt(selectedRow, 0);
Object ob=tableModel.getValueAt(selectedRow, 1);
aTextField.setText(oa.toString());
bTextField.setText(ob.toString());
}
});
scrollPane.setViewportView(table);//表格放到滚动条面板
JPanel p=new JPanel();
getContentPane().add(p,BorderLayout.SOUTH);
p.add(new JLabel("A: "));
aTextField=new JTextField("A4:",10);
p.add(aTextField);
bTextField=new JTextField("B4",10);
p.add(new JLabel("B: "));
p.add(bTextField);
JButton addButton=new JButton("添加");
addButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
String[] rowValues={aTextField.getText(),bTextField.getText()};
//想表格中添加一行
tableModel.addRow(rowValues);
int rowCount=table.getRowCount()+1;
aTextField.setText("A"+rowCount);;
bTextField.setText("B"+rowCount);
}
});
p.add(addButton);
JButton updButton=new JButton("修改");
updButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int selectedRow=table.getSelectedRow();
if(selectedRow!=-1){
tableModel.setValueAt(aTextField.getText(),selectedRow,0);
tableModel.setValueAt(aTextField.getText(),selectedRow,1);
}
}
});
p.add(updButton);
JButton delButton=new JButton("删除");
delButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int selectedRow=table.getSelectedRow();
if(selectedRow!=-1){
tableModel.removeRow(selectedRow);;
}
}
});
p.add(delButton);
setSize(600, 300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
}
public static void main(String[] args) {
new ToolTipList();
}
}
表格的增删改
最新推荐文章于 2024-07-26 00:00:00 发布