Presentation is loading. Please wait.

Presentation is loading. Please wait.

KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement.

Similar presentations


Presentation on theme: "KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement."— Presentation transcript:

1 KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement KeyListener, you must implement three methods: keyPressed, keyReleased and keyTyped all three methods receive a KeyEvent to determine which key was pressed you can pass the event the message getKeyChar( ) –in order for your Java program to watch for key presses, you also have to get your container (probably a JPanel) to watch the keyboard, this is done by saying panel.setFocusable(true); We will look at code that uses KeyListener to implement a “typewriter” and an “etch-a-sketch” type program –you might also use KeyListener for a computer game where the user uses the keyboard to control movement in the game

2 Building a Key-controlled Game Let’s build a game where you use the keys to control an object on the screen (say an image) –We will use the keys ‘a’, ‘w’, ‘d’, ‘x’ to go left, up, right, down and ‘s’ to stop the motion –The game will require a Graphics JPanel which implements ActionListener for the Timer and KeyListener for keyboard interaction –In the constructor, instantiate the timer (t=new Timer(10, this); and start the timer (t.start( );) and add the keyboard listener (addKeyListener(this);) –In the main method, add a keyboard focus instruction panel.setFocusable(true); Now we need to implement actionPerformed, keyPressed, keyTyped, keyReleased and paintComponent

3 Continued For actionPerformed, move the object on the screen (x+=dx; y+=dy) and check to see if the object has hit a boundary, and then call repaint(); –In paintComponent, do super.paintComponent(g) and then redraw the object on the screen For keyPressed, do the following: –char c=e.getKeyChar( ); –if(e==‘a’) dx--; –else if(e==‘w’) dy--; –… we will leave keyTyped and keyReleased blank (that is, implement them as { })

4 JSlider Another GUI component is the Jslider –the JSlider is a bar with a mouse-movable controller –you slide the controller from left to right or right to left We will use the JSlider to control things like –speed (as you move it to the right, the Timer’s delay can be shortened, thus speeding up your game –colors, we will see how to do this in a couple of slides where 3 JSliders control the background color We create a JSlider by initializing it with 3 values –the minimum value (left-hand side or lower limit), maximum value (right-hand side or upper limit), and initial value –JSlider redSlider = new JSlider(0, 255, 0);

5 More on JSliders You can also create vertical sliders by adding JSlider.VERTICAL at the beginning of the parameters in the instantiation –JSlider slide = new JSlider(JSlider.VERTICAL, 0, 100, 50); // initial value is 50 To use a JSlider, you need to assign the JSlider a listener (just like you did with a JButton and other GUI components) –the listener needs to implement ChangeListener, so our class’ definition that contains a JSlider will look like this: –public static class JSliderExample extends JPanel implements ChangeListener To implement a ChangeListener, you need to implement the method stateChanged, which will receive a ChangeEvent ChangeEvent has a method getValue( ) which will return the current position of the JSlider

6 JSlider Example public static class SliderPanel extends JPanel implements ChangeListener { private JSlider redSlider, greenSlider, blueSlider; private int red, green, blue; public SliderPanel() { red = green = blue = 0; redSlider = new JSlider(0, 255, 0); greenSlider = new JSlider(0, 255, 0); blueSlider = new JSlider(0, 255, 0); redSlider.addChangeListener(this); greenSlider.addChangeListener(this); blueSlider.addChangeListener(this); JPanel sliderPanel = new JPanel(new GridLayout(3, 1)); sliderPanel.add(redSlider); sliderPanel.add(greenSlider); sliderPanel.add(blueSlider); add(sliderPanel); // Add the panels to the main panel. }

7 Continued public void stateChanged(ChangeEvent e) { if(e.getSource()==redSlider) red = redSlider.getValue(); else if(e.getSource()==greenSlider) green = greenSlider.getValue(); else if(e.getSource()==blueSlider) blue = blueSlider.getValue(); repaint(); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(new Color(red, green, blue)); g.fillRect(0, 0, getWidth(), getHeight()); } Notice that we use e.getSource( ) to identify the source of the Change Event (which JSlider was used?)

8 JSpinners A JSpinner is used to control a numeric selection –it contains a textfield that has a number, and two arrows to increase or decrease the number –the user can select a value by clicking the arrows To create a JSpinner, you have to do two things –SpinnerNumberModel mod = new SpinnerNumberModel(init, min, max, step); –JSpinner spin = new JSpinner(mod); –the Model is needed to first define the range of values for the spinner –init is the initial value, min is the smallest value in the range, max is the largest value in the range, and step is the number of values that the value goes up or down by with every arrow press For instance, we might use 3 JSpinners to allow the user to change the color instead of (or addition to) the JSliders –in which case, we might define 3 JSpinners as: SpinnerNumberModel mod = new SpinnerNumberModel(0, 0, 255, 1); JSpinner redSpinner = new JSpinner(mod); JSpinner greenSpinner = new JSpinner(mod); JSpinner blueSpinner = new JSpinner(mod);

9 More on JSpinners The JSpinner will also use a ChangeListener like the JSlider which means that you must add implements ChangeListener to the class, add the listener to each JSpinner, and implement a stateChanged event –the ChangeEvent passed to the stateChanged method will include both a value and the source, just like the JSlider You can also create spinners that show lists of strings: String[] classes = {“Freshman”, “Sophmore”, “Junior”, “Senior”, “Graduate”}; –SpinnerModel model = new SpinnerListModel(classes); –JSpinner spinner = new JSpinner(model); Notice in this case, the model is a List model, not a number model –notice that you do not provide an initial value with the SpinnerListModel, instead To get the value from a Spinner, you have to be careful because spinner.getValue( ) returns an Object, so if the values are numbers, use: x = Integer.parseInt(“” + spinner.getValue( ));


Download ppt "KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement."

Similar presentations


Ads by Google