我必须使用 Windows(JFrame 和非模态 JDialog),并且我想将 JDialog 附加到 JFrame,这样当我移动 JFrame 时,JDialog 也会被移动。
同步运动本身不是问题。我是通过 ComponentListener.componentMoved(.) 实现的。

但是附件不应该是固定的。用户应该有可能通过将 JDialog 从 JFrame 移开来分离它。仅当 JDialog 直接放置到 JFrame 边框时,才应附加它。

为了帮助用户将 JDialog 准确地放置在 JFrame 旁边(附加它),我想 实现“磁效应” :如果 JDialog 移动到 JFrames 边框的距离超过 10 像素,则 JDialog 应自动放置在紧邻框架。
在 ComponentListener.componentMoved(.) 中检测到这种情况也不是问题,而是设置新的 JDialog 位置:

当我首先通过 JDialog.setLocation(.) 设置新位置时,JDialog 被正确放置。 但是当我完成对话框拖动(释放鼠标按钮)时, JDialog 被放回先前的位置(距 JFrame 10px)

我认为这是因为在拖动结束时,“系统”还调用了 setLocation(.)。
有什么想法可以防止这种行为吗?例如。从事件队列中删除任何后续的鼠标移动或鼠标释放事件?

最佳答案

我对这个问题很感兴趣,并决定制作我自己的小程序来创建一个主框架/jetty 和其他可停靠的容器。这些容器将跟随主框架以保持在它们的位置。

所以虽然回答了我想分享我的例子。

至于为什么 OPs 代码不能完美工作,我认为这是因为 componentMoved 会在每次移动时重新触发,因此在可停靠的移动过程中出现问题。

这是一个小示例,您现在可以将可停靠项添加到主框架的北、东、南和/或西。可停靠点保持在其位置的方式由诸如粘性、磁性和跟随布局之类的布局管理。

Sticky Layout 随主框架移动,而Follow 调用dockables 移动到主框架位置,而Magnetic 就像名字假设的那样吸引一定距离内的所有dockables 应该注意,虽然每个dockable ie 只被吸引到主dock,如果它在主框架内主框架上与其指定的最终/停靠点(主框架的东顶部)的给定距离。

它使用 ComponentAdapter/ListenerSwing TimerComponent#setLocation(int x,int y) 来实现结果。

下面的屏幕截图是 4 个可停靠点(北、西、东和南),中心屏幕是主框架。 Docker 类有一个 getDockToolbar,它允许我们添加一个工具栏,该工具栏具有预先构建的停靠和取消停靠按钮。

这是代码(下面显示磁性布局):

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class MagneticFrameAndDialog {

    public MagneticFrameAndDialog() {
        createAndShowGUI();

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new MagneticFrameAndDialog();
            }
        });
    }

    private void createAndShowGUI() {
        JFrame frame = new JFrame("JFrame (The Docks)");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Docker docker = new Docker();
        docker.registerDock(frame);
        docker.setLayout(Docker.MAGNETIC_LAYOUT);
        //docker.setMagneticFieldSize(250);//default is 150
        docker.setComponentMovedReactTime(50);//default is 100

        JDialog d1 = createAndShowDialog(300, 300);
        d1.setTitle("East Dockable");
        JDialog d2 = createAndShowDialog(300, 100);
        d2.setTitle("South Dockable");
        JDialog d3 = createAndShowDialog(100, 300);
        d3.setTitle("West Dockable");
        JDialog d4 = createAndShowDialog(300, 100);
        d4.setTitle("North Dockable");

        docker.registerDockee(d1, Docker.EAST_DOCKED);
        docker.registerDockee(d2, Docker.SOUTH_DOCKED);
        docker.registerDockee(d3, Docker.WEST_DOCKED);
        docker.registerDockee(d4, Docker.NORTH_DOCKED);

        frame.add(docker.getDockToolbar(), BorderLayout.SOUTH);

        frame.pack();
        frame.setVisible(true);
    }

    private JDialog createAndShowDialog(final int w, final int h) {
        JDialog dialog = new JDialog() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(w, h);
            }
        };
        dialog.setTitle("Dockable Dialog");
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.pack();
        dialog.setVisible(true);
        return dialog;
    }
}

class Docker {

    public static final String NORTH_DOCKED = "dock north", SOUTH_DOCKED = "dock south", WEST_DOCKED = " dock west", EAST_DOCKED = "dock east";
    public static final String FOLLOW_LAYOUT = "layout follow", STICKY_LAYOUT = "layout sticky", MAGNETIC_LAYOUT = "layout magnetic";
    private HashMap<Component, String> dockees = new HashMap<>();
    private Timer dockeeMoveTimer;
    private ComponentAdapter caDock, caDockee;
    private Component dock;
    private String layout = STICKY_LAYOUT;
    private int MAGNETIC_FIELD_SIZE = 150, movedReactTime = 100;

    public Docker() {
        initTimers();
        initComponentAdapters();
    }

    public void setLayout(String layout) {
        this.layout = layout;
    }

    void setComponentMovedReactTime(int milis) {
        movedReactTime = milis;
    }

    private void initComponentAdapters() {
        caDockee = new ComponentAdapter() {
            @Override
            public void componentMoved(ComponentEvent ce) {
                super.componentMoved(ce);
                if (layout.equals(MAGNETIC_LAYOUT)) {
                    createDockeeMovedTimer();
                } else {
                    iterateDockables();
                }
            }

            private void createDockeeMovedTimer() {
                if (dockeeMoveTimer.isRunning()) {
                    dockeeMoveTimer.restart();
                } else {
                    dockeeMoveTimer.start();
                }
            }
        };
        caDock = new ComponentAdapter() {
            @Override
            public void componentMoved(ComponentEvent ce) {
                super.componentMoved(ce);
                iterateDockables();
            }

            @Override
            public void componentResized(ComponentEvent ce) {
                super.componentResized(ce);
                iterateDockables();
            }
        };
    }

    private void initTimers() {
        dockeeMoveTimer = new Timer(movedReactTime, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                iterateDockables();
            }
        });
        dockeeMoveTimer.setRepeats(false);
    }

    private void iterateDockables() {
        //System.out.println("Dock will call for Dockees to come");
        for (Map.Entry<Component, String> entry : dockees.entrySet()) {
            Component component = entry.getKey();
            String pos = entry.getValue();
            if (!isDocked(component, pos)) {
                dock(component, pos);
            }
        }
    }

    void registerDock(Component dock) {
        this.dock = dock;
        dock.addComponentListener(caDock);
    }

    void registerDockee(Component dockee, String pos) {
        dockee.addComponentListener(caDockee);
        dockees.put(dockee, pos);
        caDock.componentResized(new ComponentEvent(dock, 1));//not sure about the int but w dont use it so its fine for now
    }

    void deregisterDockee(Component dockee) {
        dockee.removeComponentListener(caDockee);
        dockees.remove(dockee);
    }

    void setMagneticFieldSize(int sizeInPixels) {
        MAGNETIC_FIELD_SIZE = sizeInPixels;
    }

    private boolean isDocked(Component comp, String pos) {
        switch (pos) {
            case EAST_DOCKED:
                int eastDockedX = dock.getX() + dock.getWidth();
                int eastDockedY = dock.getY();
                if (layout.equals(MAGNETIC_LAYOUT)) {
                    if (comp.getLocation().distance(new Point(eastDockedX, eastDockedY)) <= MAGNETIC_FIELD_SIZE) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (comp.getX() == eastDockedX && comp.getY() == eastDockedY) {
                        // System.out.println("is eastly docked");
                        return true;
                    }
                }
                break;
            case SOUTH_DOCKED:
                int southDockedX = dock.getX();
                int southDockedY = dock.getY() + dock.getHeight();
                if (layout.equals(MAGNETIC_LAYOUT)) {
                    if (comp.getLocation().distance(new Point(southDockedX, southDockedY)) <= MAGNETIC_FIELD_SIZE) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (comp.getX() == southDockedX && comp.getY() == southDockedY) {
                        // System.out.println("is southly docked");
                        return true;
                    }
                }
                break;
            case WEST_DOCKED:
                int westDockedX = dock.getX() - comp.getWidth();
                int westDockedY = dock.getY();
                if (layout.equals(MAGNETIC_LAYOUT)) {
                    if (comp.getLocation().distance(new Point(westDockedX + comp.getWidth(), westDockedY)) <= MAGNETIC_FIELD_SIZE) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (comp.getX() == westDockedX && comp.getY() == westDockedY) {
                        // System.out.println("is southly docked");
                        return true;
                    }
                }
                break;
            case NORTH_DOCKED:
                int northDockedX = dock.getX() + comp.getHeight();
                int northDockedY = dock.getY() - comp.getHeight();
                if (layout.equals(MAGNETIC_LAYOUT)) {
                    if (comp.getLocation().distance(new Point(northDockedX - comp.getHeight(), northDockedY + comp.getHeight())) <= MAGNETIC_FIELD_SIZE) {
                        return false;
                    } else {
                        return true;
                    }
                } else {
                    if (comp.getX() == northDockedX && comp.getY() == northDockedY) {
                        // System.out.println("is southly docked");
                        return true;
                    }
                }
                break;
        }
        return false;
    }
    private Timer eastTimer = null, southTimer = null, westTimer = null, northTimer = null;

    private void dock(final Component comp, String pos) {
        //System.out.println("Snapping Dockee back to the dock");
        switch (pos) {
            case EAST_DOCKED:
                int eastDockedX = dock.getX() + dock.getWidth();
                int eastDockedY = dock.getY();
                if (eastTimer == null) {
                    eastTimer = getTimer(comp, eastDockedX, eastDockedY);
                    eastTimer.start();
                } else {
                    if (!eastTimer.isRunning()) {
                        eastTimer = getTimer(comp, eastDockedX, eastDockedY);
                        eastTimer.start();
                    }
                }
                break;
            case SOUTH_DOCKED:
                int southDockedX = dock.getX();
                int southDockedY = dock.getY() + dock.getHeight();
                if (southTimer == null) {
                    southTimer = getTimer(comp, southDockedX, southDockedY);
                    southTimer.start();
                } else {
                    if (!southTimer.isRunning()) {
                        southTimer = getTimer(comp, southDockedX, southDockedY);
                        southTimer.start();
                    }
                }
                break;
            case WEST_DOCKED:
                int westDockedX = dock.getX() - comp.getWidth();
                int westDockedY = dock.getY();
                if (westTimer == null) {
                    westTimer = getTimer(comp, westDockedX, westDockedY);
                    westTimer.start();
                } else {
                    if (!westTimer.isRunning()) {
                        westTimer = getTimer(comp, westDockedX, westDockedY);
                        westTimer.start();
                    }
                }
                break;
            case NORTH_DOCKED:
                int northDockedX = dock.getX();
                int northDockedY = dock.getY() - comp.getHeight();
                if (northTimer == null) {
                    northTimer = getTimer(comp, northDockedX, northDockedY);
                    northTimer.start();
                } else {
                    if (!northTimer.isRunning()) {
                        northTimer = getTimer(comp, northDockedX, northDockedY);
                        northTimer.start();
                    }
                }
                break;
        }
    }

    private Timer getTimer(final Component comp, int finalX, int finalY) {
        Timer t = null;
        switch (layout) {
            case STICKY_LAYOUT:
                t = stickyDockableTimer(comp, finalX, finalY);
                break;
            case FOLLOW_LAYOUT:
                t = followDockableTimer(comp, finalX, finalY);
                break;
            case MAGNETIC_LAYOUT:
                t = followDockableTimer(comp, finalX, finalY);
                break;
        }
        return t;
    }

    private Timer followDockableTimer(final Component comp, final int finalX, final int finalY) {
        Timer t = new Timer(1, new AbstractAction() {
            int INCREMENT = 1, DECREMENT = 1;
            int x = comp.getX(), y = comp.getY();

            @Override
            public void actionPerformed(ActionEvent ae) {
                //System.out.println(finalX + "," + finalY);
                if (x < finalX) {
                    x += INCREMENT;
                } else if (x > finalX) {
                    x -= DECREMENT;
                }
                if (y < finalY) {
                    y += INCREMENT;
                } else if (y > finalY) {
                    y -= DECREMENT;
                }
                comp.setLocation(x, y);
                if (x == finalX && y == finalY) {
                    if (comp instanceof Window) {
                        ((Window) comp).toFront();
                    }
                    ((Timer) ae.getSource()).stop();
                }
            }
        });
        return t;
    }

    public JPanel getDockToolbar() {
        JPanel panel = new JPanel();
        for (Map.Entry<Component, String> entry : dockees.entrySet()) {
            final Component component = entry.getKey();
            String pos = entry.getValue();
            Docker.MyButton jtb = new Docker.MyButton("un-dock" + pos.replace("dock", ""), component, pos);
            panel.add(jtb);
            jtb.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent ae) {
                    Docker.MyButton jtb = (Docker.MyButton) ae.getSource();
                    String tmp = jtb.getText();
                    if (tmp.contains("un-dock")) {
                        jtb.setText(tmp.replace("un-dock", "dock"));
                        deregisterDockee(jtb.getComponent());
                    } else {
                        jtb.setText(tmp.replace("dock", "un-dock"));
                        registerDockee(jtb.getComponent(), jtb.getDockablePosition());
                    }
                }
            });
        }
        return panel;
    }

    private Timer stickyDockableTimer(final Component comp, final int finalX, final int finalY) {
        Timer t = new Timer(1, new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                comp.setLocation(finalX, finalY);
            }
        });
        t.setRepeats(false);
        return t;
    }

    private class MyButton extends JButton {

        private final Component c;
        private final String pos;

        public MyButton(String text, Component c, String pos) {
            super(text);
            this.c = c;
            this.pos = pos;
        }

        public Component getComponent() {
            return c;
        }

        public String getDockablePosition() {
            return pos;
        }
    }
}

关于java - 将窗口对话框或框架附加到另一个的磁性效果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14091901/

10-13 03:34