9

我有 JScrollPane,其中包含水平行中的一些图像。如果图像行对于视口来说太长,JScrollPane 会显示一个滚动条,从而降低视口的高度。我想调整图像大小以适应视口。我怎样才能检测到视口改变了它的大小?不幸的是,注册更改事件处理程序似乎不起作用。

4

2 回答 2

13

在 ViewPort 上使用更改侦听器似乎对我有用。这是一个小演示:

import java.awt.BorderLayout;
import java.io.UnsupportedEncodingException;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main {

    public static void main(String[] args) throws UnsupportedEncodingException {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel(new BorderLayout());
        final JPanel buttons = new JPanel();
        final JScrollPane pane = new JScrollPane(buttons);
        pane.getViewport().addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                System.err.println("Change in " + e.getSource());
                System.err.println("Vertical visible? " + pane.getVerticalScrollBar().isVisible());
                System.err.println("Horizontal visible? " + pane.getHorizontalScrollBar().isVisible());
            }
        });
        panel.add(pane);
        frame.setContentPane(panel);
        frame.setSize(300, 200);
        frame.setVisible(true);
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {

            @Override
            protected Void doInBackground() throws Exception {
                for (int i = 0; i < 10; i++) {
                    Thread.sleep(800);
                    buttons.add(new JButton("Hello " + i));
                    buttons.revalidate();
                }
                return null;
            }
        };
        worker.execute();
    }
}
于 2012-05-02T09:50:16.217 回答
1

我用HierarchyBoundsListener来检测 JScrollPane 大小的变化:

onAncestorResized(scroll, evt -> resizeYourImages());

这是附加侦听器的便捷方法:

static void onAncestorResized(JComponent component, Consumer<HierarchyEvent> callback) {
    component.addHierarchyBoundsListener(new HierarchyBoundsAdapter() {
        @Override
        public void ancestorResized(HierarchyEvent e) {
            callback.accept(e);
        }
    });
}
于 2016-03-10T18:03:45.060 回答