0

我在我的 中添加了一个ComponentAdapterComponentListenerJDialog想实现componentResized(ComponentEvent e). 目标是保持JDialog的比率,并且为了计算如何根据用户的操作调整它的大小,我想知道用户是否拖动了窗口的侧边缘、窗口的顶部/底部边缘或其中之一窗户的角落

有没有办法从 中检索该信息ComponentEvent

4

1 回答 1

0

我不知道我原来的问题的答案(有没有办法告诉来源ComponentEvent),所以我只存储以前的尺寸,并计算新的尺寸。如果它对任何人有帮助,这就是我正在使用的代码。请享用:

public class ResizableImageView extends JDialog {
    BufferedImage img;
    Dimension OriginalImgSize;
    double imageRatio;
    JPanel jp;
    JLabel label;
    Dimension previousSize;

    public ResizableImageView(BufferedImage img) {

        ...

        setResizable(true);
        this.img = img;
        OriginalImgSize = new Dimension(img.getWidth(), img.getHeight());
        imageRatio = (double)img.getWidth() / (double)img.getHeight();

        label = new JLabel(new ImageIcon(img));
        label.setMinimumSize(OriginalImgSize);
        jp = new JPanel();
        jp.setBorder(new EmptyBorder(0, 0, 0, 0));
        jp.add(label);
        setContentPane(jp);
        pack();
        previousSize = getSize();

        addComponentListener(new ComponentAdapter() {
            private boolean allreadyResized = true;

            private void resize(Image img) {
                ImageIcon ico = new ImageIcon(img);
                label = new JLabel(ico);
                label.setBorder(new EmptyBorder(0, 0, 0, 0));
                label.setPreferredSize(new Dimension(img.getWidth(null), img.getHeight(null)));
                jp = new JPanel();
                jp.setBorder(new EmptyBorder(0, 0, 0, 0));
                jp.add(label);
                setContentPane(jp);
                allreadyResized = true;
                pack();
                previousSize = getSize();
            }

            @Override
            public void componentResized(ComponentEvent e) {
                if (allreadyResized) {
                    allreadyResized  = false;
                    return;
                }
                double xChange = (double) Math.abs(getSize().width - previousSize.width);
                double yChange = (double) Math.abs(getSize().height - previousSize.height);
                if (xChange == 0 && yChange == 0) return; 
                int height = getSize().height - getInsets().bottom - getInsets().top;
                int width = getSize().width - getInsets().left - getInsets().right;

                if (height > OriginalImgSize.height 
                        || width > OriginalImgSize.width) {
                    resize(img);
                    return;
                }
                if (yChange == 0 || xChange/yChange > imageRatio) {
                    resize(img.getScaledInstance(width, -1, Image.SCALE_SMOOTH));
                    return;
                } else {
                    resize(img.getScaledInstance(-1, height, Image.SCALE_SMOOTH));
                    return;
                }
            }
        });
    }
}
于 2013-06-13T15:44:24.853 回答