• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JScrollBar, key events

 
Alex Carter
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have a strange problem. Here is an example:


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class myFrame extends JFrame
{
JPanel panel1;

public myFrame()
{
panel1 = new JPanel();
panel1.setLayout(null);

JScrollBar sb = new JScrollBar(JScrollBar.HORIZONTAL, 1, 20, 0, 100);
sb.setSize(new Dimension(191, 17));

this.setContentPane(panel1);
//panel1.add(sb);

this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == 32)
{
System.out.println("SPACE pressed");
}

if (e.getKeyCode() == 27)
{
System.out.println("ESC pressed");
}
}

public void keyReleased(KeyEvent e)
{

}
});
}

public static void main (String[] args)
{
myFrame mf = new myFrame();
mf.setLocation(200, 200);
mf.setSize(200, 200);
mf.setVisible(true);
}
}



This program creates a new frame, sets a panel as it's content pane, and adds a key listener to respond when the user presses a key on the keyboard. Note the commented-out line on line 20 - which uses 'panel1.add(sb)' to add a JScrollBar to the application.

Now, when you run it normally the program works fine - it responds to the key presses. But when you un-comment line 20 so that it adds the scrollbar to the app, it stops responding to the key events!

Why is this? Any suggestions of how I can solve this (with sample code if poss.) very much appreciated!

Thanks.

A.C.
 
Craig Wood
Ranch Hand
Pie
Posts: 1535
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check out the section Making a Custom Component Focusable on the page How to Use the Focus Subsystem in the java tutorial. This section links to this page How to Use Key Bindings.
 
Alex Carter
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Many thanks!

I will give it a go.


A.C.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic