我正在尝试将JPanel编码为绘制数字的空间。为此,我将布局设置为null
mainPanel.setLayout(null);
然后,我在主面板中插入了一些按钮,试图实现拖放功能。
btn.setTransferHandler(new TransferHandler("text"));
btn.addMouseListener(new MouseAdapter(){
public void mouseDragged(MouseEvent e){
Dimension size=btn.getPreferredSize();
JButton button = (JButton)e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
}
});
我的问题是,我可以在null布局中使用TransferHandler吗? 一旦我开始拖动东西,鼠标光标就会变成这样的形状: forbidden action
答案 0 :(得分:2)
TransferHandler用于传输数据,而不是移动面板周围的按钮。所以布局没有效果。
在您的情况下,您正在为“text”设置TransferHandler,这意味着您正在尝试将按钮的“文本”传输到其他组件。
btn.addMouseListener(new MouseAdapter(){
public void mouseDragged(MouseEvent e){
Dimension size=btn.getPreferredSize();
JButton button = (JButton)e.getSource();
TransferHandler handle = button.getTransferHandler();
handle.exportAsDrag(button, e, TransferHandler.COPY);
}
});
MouseListener中没有mouseDragged
个事件。 mouseDragged
事件在MouseMotionListener中生成。
当我将MouseListener添加到DnD支持的组件时,我总是将逻辑添加到mousePressed
事件中。
阅读Drag and Drop and Data Transfer上Swing教程中的部分,了解更多信息和示例,以帮助您入门。
答案 1 :(得分:0)
在阅读了之前的答案并阅读@camickr发布的文档后,我注意到transferHandler并不是我正在搜索的内容。我需要的是围绕单个JPanel移动组件,而不是将其副本拖放到不同的面板或组件。我最终得到的只是使用组件的setLocation函数,结合MouseEvents和mouseMotionListeners。
protected class DragProcessor extends MouseAdapter implements MouseListener, MouseMotionListener {
Point pressPoint;
Point releasePoint;
@Override
public void mouseDragged(MouseEvent e) {
Point dragPoint = e.getPoint();
int xDiff = pressPoint.x - dragPoint.x;
int yDiff = pressPoint.y - dragPoint.y;
Rectangle b = button.getBounds();
Point p = b.getLocation();
SwingUtilities.convertPointToScreen(p, button.getParent());
p.x -= xDiff;
p.y -= yDiff;
SwingUtilities.convertPointFromScreen(p, button.getParent());
button.setLocation(p);
repaint();
}
@Override
public void mousePressed(MouseEvent e){
pressPoint = e.getPoint();
button = (JButton)e.getSource();
}
@Override
public void mouseReleased(MouseEvent e){
releasePoint = e.getPoint();
if (e.getButton() == MouseEvent.BUTTON3) {
// do whatever it is when the right button is pressed
} else {
int xDiff = pressPoint.x - releasePoint.x;
int yDiff = pressPoint.y - releasePoint.y;
Rectangle b = button.getBounds();
Point p = b.getLocation();
SwingUtilities.convertPointToScreen(p, panel.getParent());
p.x -= xDiff;
p.y -= yDiff;
SwingUtilities.convertPointFromScreen(p, panel.getParent());
if (p.x <= 0) {
p.x = 1;
}
if (p.x > panel.getParent().getWidth() - b.width) {
p.x = panel.getParent().getWidth() - b.width;
}
if (p.y <= 0) {
p.y = 1;
}
if (p.y > panel.getParent().getHeight() - b.height) {
p.y = panel.getParent().getHeight() - b.height;
}
button.setLocation(p);
getParent().repaint();
}
}
}
DragProcessor dragProcessor = new DragProcessor();
myButton.getMainButton().addMouseMotionListener(dragProcessor);
myButton.getMainButton().addMouseListener(dragProcessor);