Isn't there a way to scroll a scrollable Swing component without this component (and another) has focus?
Then general solution is to use Key Bindings.
However, the problem is that each component can implement Key Bindings itself for the up/down event, in which case the related Action
for that component is invoked.
The tutorial demonstrates how you can remove key bindings from a component.
a JTable and some textboxes
So these are examples of components the do implement up/down key bindings.
JButton controls
Is an example of a component that doesn't have default up/down key bindings.
So you could add your own with code like the following:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class SSCCE extends JPanel
{
public SSCCE()
{
setLayout( new BorderLayout() );
JPanel top = new JPanel();
top.add( new JTextField(10) );
top.add( new JButton("Button") );
add(top, BorderLayout.PAGE_START);
JLabel label = new JLabel( new ImageIcon("mong.jpg") );
JScrollPane scrollPane = new JScrollPane( label );
add(scrollPane, BorderLayout.CENTER);
JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
InputMap im = getInputMap(JScrollBar.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
ActionMap am = getActionMap();
im.put(KeyStroke.getKeyStroke("pressed UP"), "up");
am.put("up", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
scrollBar.setValue(scrollBar.getValue() - scrollBar.getUnitIncrement(-1));
}
});
im.put(KeyStroke.getKeyStroke("pressed DOWN"), "down");
am.put("down", new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
scrollBar.setValue(scrollBar.getValue() + scrollBar.getUnitIncrement(1));
}
});
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SSCCE());
frame.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );
}
public static void main(String[] args) throws Exception
{
java.awt.EventQueue.invokeLater( () -> createAndShowGUI() );
}
}
In the above example the image will scroll when focus is on the button, but not on the text field.