How Do I Set the Focus to a <JPanel> Object?

K

kvnsmnsn

I had a program running some time back that brought up a <JPanel> ob-
ject embedded in a <JFrame> object and let the user enter characters
on the keyboard to control execution of the program. I've written the
code below to let the user enter keys and have them simply written to
the <JPanel> object using the <drawString()> method. However, when I
run this program and enter keys from the alphabet nothing happens. If
I remember right I need to set the focus on the <JPanel> object, or
something like that, but I don't remember how to do that. Does anybo-
dy know how I can set the focus so I can get this program working?

---thanks,
Kevin Simonson

"You'll never get to heaven, or even to LA,
if you don't believe there's a way."
from _Why Not_

####################################################################

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;

public class KeyTester extends JPanel
{
String enteredLine;
int width;
int height;
Color clr;

protected KeyTester ( int wdth
, int hght)
{
width = wdth;
height = hght;
addKeyListener( new KeyLstnr());
setPreferredSize( new Dimension( width, height));
setBackground( Color.green);
enteredLine = "";
}

protected void paintComponent ( Graphics page)
{
super.paintComponent( page);
page.setColor( clr);
page.drawString( enteredLine, width >> 1, height >> 1);
}

private class KeyLstnr implements KeyListener
{
public void keyPressed ( KeyEvent keyEvnt)
{
enteredLine += keyEvnt.getKeyChar();
clr = Color.red;
repaint();
}

public void keyReleased ( KeyEvent keyEvnt)
{
clr = Color.blue;
repaint();
}

public void keyTyped ( KeyEvent keyEvnt) {}
}

public static void main ( String[] arguments)
{
JFrame kFrame;
KeyTester kPanel;

if (arguments.length == 2)
{ kFrame = new JFrame( "For entering keys.");
kPanel
= new KeyTester
( Integer.parseInt( arguments[ 0])
, Integer.parseInt( arguments[ 1]));
kFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
kFrame.getContentPane().add( kPanel);
kFrame.pack();
kFrame.setVisible( true);
}
else
{ System.out.println( "Usage is\n java KeyTester <width>
<height>");
}
}
}
 
A

Andrew T.

protected KeyTester ( int wdth
, int hght)
{
width = wdth;
height = hght;
addKeyListener( new KeyLstnr());
setPreferredSize( new Dimension( width, height));
setBackground( Color.green);
enteredLine = "";

setFocusable(true);

HTH

Andrew T.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top