aspose file tools*
The moose likes Swing / AWT / SWT and the fly likes JScrollBar, key events Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JScrollBar, key events" Watch "JScrollBar, key events" New topic
Author

JScrollBar, key events

Alex Carter
Greenhorn

Joined: Oct 28, 2004
Posts: 2
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

Joined: Jan 14, 2004
Posts: 1535
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

Joined: Oct 28, 2004
Posts: 2
Many thanks!

I will give it a go.


A.C.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: JScrollBar, key events