Reputation: 23
I'm trying to implement my own logic for left and right arrow keys in a JSlider. By default the JSlider moves the slider left and right based off of the left and right arrows. The only way I could stop it from moving the slider is to set setFocusable to false, but that prevents my addKeyListener from working. Is there any way to override or turn off this default action so my addKeyListener is the only method responding to the key events?
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class slider {
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI() {
//Create and set up the window.
JFrame frame = new JFrame("Slider Test");
JSlider slider = new JSlider();
slider.setToolTipText("Slide the time.");
slider.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
slider.setOpaque(false);
slider.setPaintTrack(true);
slider.setPaintTicks(true);
slider.setPaintLabels(false);
slider.setMinimum(0);
slider.setMaximum(100);
slider.setMajorTickSpacing(20);
slider.setMinorTickSpacing(5);
slider.setOrientation(JSlider.HORIZONTAL);
slider.setSnapToTicks(false);
slider.setFocusable(true);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
System.out.println("I have changed :(");
}
});
slider.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
// right arrow
if(keyCode == 39) {
System.out.println("do right arrow key logic");
}
// left arrow
if(keyCode == 37) {
System.out.println("do left arrow key logic");
}
}
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(slider);
frame.pack();
frame.setVisible(true);
}
}
Upvotes: 1
Views: 577
Reputation: 324207
Don't use a KeyListener.
Swing was designed to be used with Key Bindings. If you don't like the default Action for a given key binding then you can replace the Action.
Check out Key Bindings for more information that shows the default bindings for a given component as well as how to replace the Action for your right/left KeyStroke.
The basics to change existing functionality by replacing the Action
of an existing binding is:
Action action = new AbstractAction() {...};
KeyStroke keyStroke = KeyStroke.getKeyStroke(...);
InputMap im = component.getInputMap(...);
component.getActionMap().put(im.get(keyStroke), action);
Upvotes: 4