I have JScrollPane that contains some images in a horizontal row. If the row of images is too long for the view port, the JScrollPane shows a scroll bar, reducing the height of the view port. I'd like to resize the images to fit the view port. How can I detect that the view port changed its size? Unfortunately, registering change event handlers doesn't seem to work.
A JScrollBar is a component and it doesn't handle its own events whereas a JScrollPane is a Container and it handles its own events and performs its own scrolling.
You need to use setOpaque(false) to make it transparent. Call that both on the JScrollPane, and on it's ViewPort. sp. setOpaque(false); sp.
FieldScrollPanelLayout FieldIt is scrollpane's horizontal scrollbar child. It displays policy for the horizontal scrollbar. This displays the lower left corner.
JList doesn't support scrolling directly. To create a scrolling list you make the JList the viewport view of a JScrollPane. For example: JScrollPane scrollPane = new JScrollPane(dataList); // Or in two steps: JScrollPane scrollPane = new JScrollPane(); scrollPane.
Using change listener on the ViewPort seems to work for me. Here is a small demo of that:
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With