JTable 行拖动和数据拖拽

maxinliangGenius 2011-05-02 11:19:59
我写了二个类,想实现JTable的行拖动和数据拖到其它Jtable,现在完成的并不是太完美,希望高人帮忙指点和修改一下,小弟万分感谢谢,行拖动的是我用的网上的一个:DragDropRowTableUI.java. 我改了其中一点代码。我把代码发出来如下:

import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceMotionListener;
import java.awt.event.MouseEvent;
import java.io.IOException;

import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.TransferHandler;
import javax.swing.event.MouseInputListener;
import javax.swing.plaf.basic.BasicTableUI;
import javax.swing.table.TableModel;

public class DragDropRowTableUI extends BasicTableUI{

private boolean draggingRow = false;
private int startDragPoint;
private int dyOffset;
public DragDropRowTableUI() {

}

protected MouseInputListener createMouseInputListener() {
DragDropRowMouseInputHandler dss=new DragDropRowMouseInputHandler();

DragSource ds = DragSource.getDefaultDragSource();
ds.addDragSourceMotionListener(dss);
ds.createDefaultDragGestureRecognizer(table, DnDConstants.ACTION_COPY_OR_MOVE, dss);
// ds.startDrag(null, null, o, null);
return dss;
}

public void paint(Graphics g, JComponent c) {
super.paint(g, c);

if (draggingRow) {
g.setColor(table.getParent().getBackground());
Rectangle cellRect = table.getCellRect(table.getSelectedRow(), 0, false);
g.copyArea(cellRect.x, cellRect.y, table.getWidth(),
table.getRowHeight(), cellRect.x, dyOffset);

if (dyOffset < 0) {
g.fillRect(cellRect.x, cellRect.y
+ (table.getRowHeight() + dyOffset), table.getWidth(), (dyOffset * -1));
} else {
g.fillRect(cellRect.x, cellRect.y, table.getWidth(),
dyOffset);
}
}
}


class DragDropRowMouseInputHandler extends MouseInputHandler implements DragGestureListener, Transferable ,DragSourceMotionListener {

public void mousePressed(MouseEvent e) {
super.mousePressed(e);
startDragPoint = (int) e.getPoint().getY();
}

public void mouseDragged(MouseEvent e) {


}

public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);

draggingRow = false;
table.repaint();
}

public void dragGestureRecognized(DragGestureEvent event) {

try {
Cursor cursor = null;
if (event.getDragAction() == DnDConstants.ACTION_MOVE) {
cursor = DragSource.DefaultMoveDrop;

}

event.startDrag(cursor, this);

} catch (Exception e) {
e.printStackTrace();
}
}

public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.stringFlavor};
}

public boolean isDataFlavorSupported(DataFlavor flavor) {
return true;
}

public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
//crate id's string in table
StringBuffer sb = new StringBuffer();
for (int i = 0; i < table.getSelectedRows().length; i++) {
sb.append(table.getValueAt(table.getSelectedRows()[i], 0) + ",");
}
if (sb.length() > 0) {
return sb.substring(0, sb.length() - 1);
}
return table;
}

public void dragMouseMoved(DragSourceDragEvent e) {
int fromRow = table.getSelectedRow();

if (fromRow >= 0) {
draggingRow = true;

int rowHeight = table.getRowHeight();
int middleOfSelectedRow = (rowHeight * fromRow)
+ (rowHeight / 2);

int toRow = -1;
int yMousePoint = (int) e.getY();

if (yMousePoint < (middleOfSelectedRow - rowHeight)) {
// Move row up
toRow = fromRow - 1;
} else if (yMousePoint > (middleOfSelectedRow
+ rowHeight)) {
// Move row down
toRow = fromRow + 1;
}
table.setTransferHandler(new TransferHandler("aaaa"));
/* if(!(SwingUtilities.getDeepestComponentAt(table.getParent() , e.getX(), e.getY()) instanceof JTable)){
DragSource ds = DragSource.getDefaultDragSource();
ds.createDefaultDragGestureRecognizer(table, DnDConstants.ACTION_COPY_OR_MOVE, a);
}*/
if (toRow >= 0 && toRow < table.getRowCount()) {
TableModel model = table.getModel();

for (int i = 0; i
< model.getColumnCount(); i++) {
Object fromValue =
model.getValueAt(fromRow, i);
Object toValue =
model.getValueAt(toRow, i);

model.setValueAt(toValue,
fromRow, i);
model.setValueAt(fromValue, toRow, i);
}
table.setRowSelectionInterval(toRow,
toRow);
startDragPoint = yMousePoint;
}

dyOffset = (startDragPoint - yMousePoint) * -1;
table.repaint();
}
}
}



}




import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceMotionListener;

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

/*
* NewJFrame.java
*
* Created on 2011-5-2, 15:53:17
*/

/**
*
* @author Administrator
*/
public class NewJFrame extends javax.swing.JFrame {

/** Creates new form NewJFrame */
public NewJFrame() {
initComponents();
DragDropRowTableUI o=new DragDropRowTableUI();
jTable1.setUI(o);
}

/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setName("Form"); // NOI18N

jScrollPane1.setName("jScrollPane1"); // NOI18N

jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "33", "4", "5"},
{"11", "3", "4", "5"},
{"2", "33", "44", "5"},
{"223333", "3", "4", null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
jTable1.setName("jTable1"); // NOI18N
jScrollPane1.setViewportView(jTable1);
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(desktopapplication1.DesktopApplication1.class).getContext().getResourceMap(NewJFrame.class);
jTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jTable1.columnModel.title0")); // NOI18N
jTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jTable1.columnModel.title1")); // NOI18N
jTable1.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jTable1.columnModel.title2")); // NOI18N
jTable1.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jTable1.columnModel.title3")); // NOI18N

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(25, Short.MAX_VALUE))
);

pack();
}// </editor-fold>

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration

}
...全文
253 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧