Hi there Im developing an application in Java (in a mac). When the user press the arrow down I wanted it to do something.
My code is the following:
public class Main {
static JScrollPane scrollPane;
public static void main(String[] args) {
JFrame f = new JFrame();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
f.setBounds(0, 0, dim.width, dim.height);
StandartPanel p = new StandartPanel();
f.add(p);
JToolBar tb = new JToolBar();
tb.add(new JButton("button"));
f.add(tb);
f.setVisible(true);
}
}
Its simply a program that creates a JFrame and puts in it a StandartPanel and a JToolBar which has a button.
The code of the StandartPanel is the following:
public class StandartPanel extends JPanel {
public StandartPanel () {
for( int i = 0; i < 10; i++)
this.add(new JLabel("Jlabel number: " + i));
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "forward");
this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "forward");
this.getActionMap().put("forward", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("pressed");
}
});
}
}
The for loop is not important, the important is that it prints "pressed" when D or Down is pressed.
When I actually press D it prints "pressed" but when I click down it does nothing.
After trying some things I have discover that if instead of adding a JButton to the JToolBar I add a JLabel it works (if I don't add anything it also works).
So adding a JButton to the JToolBar somehow stops the key binding working with the down button.
Any ideas of why it is happening and how it could be fixed??
Thank you!