就是實現點擊→實現內容的傳遞。點擊←刪除該行。 但是我實現時卻出現了這樣的問題。。簡單的示例
簡單的點擊添加值之後,會將之前的全部替換。一頭霧水- -。。求大神講解
簡單源碼如下。
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);
}
}
rowData = new Vector(); //加上
rowData.add("4");
rowData.add("5");
rowData.add("6");
rowData.add("7");