我有以下代码在屏幕上产生两个单独的.png。这些.pngs是用鼠标移动的,一切都运行良好,除了当它们被拖动时,它们似乎在某种类型的图层下,并且在拖动超过一英寸时消失。任何建议都很受欢迎。
import java.awt.*;
import javax.swing.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
public class TestMouseDrag {
public static void main(String[] args) {
new TestMouseDrag();
}
public TestMouseDrag() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\Hobbit.png"));
frame.add(new DragMyIcon("C:\\Users\\anon\\Desktop\\alien.png"));
frame.setSize(800,800);
frame.setVisible(true);
}
});
}
public class DragMyIcon extends JPanel {
public static final long serialVersionUID = 172L;
private JLabel label;
public DragMyIcon(String path) {
ImageIcon icon = null;
icon = new ImageIcon(path);
label = new JLabel(icon);
add(label);
MouseHandler handler = new MouseHandler();
label.addMouseListener(handler);
label.addMouseMotionListener(handler);
}
}
protected class MouseHandler extends MouseAdapter {
private boolean active = false;
private int xDisp;
private int yDisp;
@Override
public void mousePressed(MouseEvent e) {
active = true;
JLabel label = (JLabel) e.getComponent();
xDisp = e.getPoint().x - label.getLocation().x;
yDisp = e.getPoint().y - label.getLocation().y;
label.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
@Override
public void mouseReleased(MouseEvent e) {
active = false;
JLabel label = (JLabel) e.getComponent();
label.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseDragged(MouseEvent e) {
if (active) {
JLabel label = (JLabel) e.getComponent();
Point point = e.getPoint();
label.setLocation(point.x - xDisp, point.y - yDisp);
label.invalidate();
label.repaint();
}
}
@Override
public void mouseMoved(MouseEvent e) {
}
}}
答案 0 :(得分:1)
只需@Override
getPreferredSize
JPanel
,只需pack()
您的框架,而不是设置尺寸,而且效果正常。
frame.pack();
...
public class DragMyIcon extends JPanel {
...
@Override
public Dimension getPreferredSize() {
return new Dimension(400, 600);
}
}
关于这一点的事情记住,这些是两个单独的面板(因为您创建了两个单独的DragMyIcon
实例),因此您只能将标签移动到包含面板的范围。如果您希望能够在屏幕上移动它们,则需要将它们添加到同一个面板中。