考慮我有以下代碼:爪哇 - 註冊父的JPanel到的MouseEvent
public LSUIEditingPanel(LSView view) {
super();
parent = view;
controller = view.getController();
LayoutManager overlay = new OverlayLayout(this);
setLayout(overlay);
scribbleArea = new LSScribblePanel();
scribbleArea.setOpaque(false);
add(scribbleArea);
viewArea = new LSCanvasViewport(view);
add(viewArea);
setAutoscrolls(true);
drawListener = new SVGEditorDrawMouseAdaptor();
}
其中scribbleArea和viewArea都是定製的JPanel。它們都是添加到主面板的子面板。
現在我想讓它能夠將MouseEvent註冊到父面板本身,這是我可以對面板進行平移,因爲父面板將在實例化後嵌入到JScrollPane中。
這是代碼段執行拖動:
public class LSPanMouseAdapter extends MouseAdapter {
/**
* Panning pivot point
*/
private final Point panPoint = new Point();
/**
* {@inheritDoc}<p>
* Set pan starting point to be the point where the mouse currently located, and change the
* current cursor to <code>HAND_CURSOR</code>.
*/
@Override
public void mousePressed(MouseEvent event) {
JViewport viewport = (JViewport) event.getSource();
JComponent component = (JComponent) viewport.getView();
panPoint.setLocation(event.getPoint());
component.setCursor(new Cursor(Cursor.HAND_CURSOR));
}
/**
* {@inheritDoc}<p>
* Reset cursor to <code>DEFAULT_CURSOR</code>.
*/
@Override
public void mouseReleased(MouseEvent event) {
JViewport viewport = (JViewport) event.getSource();
JComponent component = (JComponent) viewport.getView();
component.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
/**
* {@inheritDoc}<p>
* Get the current viewport of the canvas and move the viewable area respective to the
* event cursor location.
*/
@Override
public void mouseDragged(MouseEvent event) {
JViewport viewport = (JViewport) event.getSource();
JComponent component = (JComponent) viewport.getView();
Point currentPoint = event.getPoint();
Point viewPoint = viewport.getViewPosition();
viewPoint.translate(panPoint.x - currentPoint.x, panPoint.y - currentPoint.y);
component.scrollRectToVisible(new Rectangle(viewPoint, viewport.getSize()));
panPoint.setLocation(currentPoint);
}
}
我試圖註冊該事件,但父面板不火的情況下,我應該怎麼做什麼建議嗎?
我沒有看到任何將MouseListener添加到父面板的位置,因此將調用事件回調函數。也不會因爲孩子面板在父母面前而接收鼠標事件嗎? (我不記得他們是否傳播到底層組件。) – 2013-05-06 12:30:31
爲了更快地發佈[SSCCE](http://sscce.org/),更好的幫助,短的,可運行的,可編譯的,仍然不知道爲什麼有JViewport和scrollRectToVisible和DragAndDrop ???,在我的mind_readers單元格中沒有電池,之前什麼都可能檢查SwingUtilities#convert ... – mKorbel 2013-05-06 12:32:14
@mKorbel對不起,冗長的代碼,但感謝您的提醒convertMouseEvent =) – 2013-05-06 13:52:18