就是实现点击→实现内容的传递。点击←删除该行。 但是我实现时却出现了这样的问题。。简单的示例
简单的点击添加值之后,会将之前的全部替换。一头雾水- -。。求大神讲解
简单源码如下。
package com.test;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Jtable extends JFrame {
private JPanel contentPane;
private JTable table;
private JButton btnNewButton;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Jtable frame = new Jtable();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Jtable() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JScrollPane scrollPane = new JScrollPane(table);
contentPane.add(scrollPane);
Vector columnNames = new Vector();
for(int i=0;i<4;i++){
columnNames.add("第" +(i+1) + "列");
}
Vector rowData = new Vector();
Vector data = new Vector();
//开始表中的数据是1,2,3,4
rowData.add("1");
rowData.add("2");
rowData.add("3");
rowData.add("4");
data.add(rowData);
//使用DefaultTableModel构建表格
DefaultTableModel tableModel = new DefaultTableModel(data,columnNames);
table = new JTable(tableModel);
scrollPane.setViewportView(table);
btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rowData.add("4");
rowData.add("5");
rowData.add("6");
rowData.add("7");
data.add(rowData);
tableModel.setDataVector(data, columnNames);
table.setModel(tableModel);
}
});
scrollPane.setRowHeaderView(btnNewButton);
}
}