JTable获取剪切板转置粘贴
时间: 2024-01-01 10:36:23 浏览: 162
您可以使用以下代码来实现JTable获取剪切板数据,并进行转置粘贴:
```java
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MainFrame extends JFrame {
private JTable table;
public MainFrame() {
setTitle("JTable Clipboard Example");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// 创建表格模型
DefaultTableModel model = new DefaultTableModel();
model.setColumnIdentifiers(new Object[]{"Column 1", "Column 2", "Column 3"});
model.addRow(new Object[]{"1", "2", "3"});
model.addRow(new Object[]{"4", "5", "6"});
model.addRow(new Object[]{"7", "8", "9"});
// 创建表格
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane, BorderLayout.CENTER);
// 创建按钮
JButton btnPaste = new JButton("Paste");
btnPaste.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pasteFromClipboard();
}
});
getContentPane().add(btnPaste, BorderLayout.SOUTH);
pack();
}
private void pasteFromClipboard() {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = clipboard.getContents(this);
if (transferable != null && transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
try {
String clipboardData = (String) transferable.getTransferData(DataFlavor.stringFlavor);
String[] lines = clipboardData.split("\n");
DefaultTableModel model = (DefaultTableModel) table.getModel();
int startRow = table.getSelectedRow();
int startCol = table.getSelectedColumn();
for (int i = 0; i < lines.length; i++) {
String[] rowData = lines[i].split("\t");
for (int j = 0; j < rowData.length; j++) {
int row = startRow + i;
int col = startCol + j;
if (row < model.getRowCount() && col < model.getColumnCount()) {
model.setValueAt(rowData[j], row, col);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainFrame().setVisible(true);
}
});
}
}
```
上述代码创建了一个包含JTable和一个"粘贴"按钮的窗口。点击"粘贴"按钮时,将会从剪贴板获取数据,并将其转置粘贴到JTable中。请注意,此代码仅处理文本数据,并且要求表格中至少有一个单元格被选中。
阅读全文