JFrame KeyListener
Im trying to get a JFrame to be updated when the user presses F12. I have added a KeyListener however I get no response. This is my implementation of the KeyListener:
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){}
public void keyPressed(KeyEvent e){
System.out.println("YES");
if (e.getKeyCode()==e.VK_F12) {
System.out.println("YES");
load();
Any ideas why its not working?
Cheers, Adam
In the future, Swing related questions should be posted in the Swing forum.
[url http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]How to Use Key Bindings
If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.
Similar Messages
-
Weird keylistener problem...
I just upgraded my java to 1.4.2 which caused this problem i believe. I add an action listener with the following code:
this.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e) {
main_keyPressed(e);
});This worked fine in an older version of java, but in 1.4.2 it doesnt get my keyinput from the frame. 'this' refers to my class that extends JFrame... Im not sure what is wrong... maybe I added it to the wrong object even though it worked fine with another version of java.
Thanks for your help,
CoWIf a control on the JFrame has the focus it needs to have the KeyListener, as in the appended code. In this case the JFrame passes the KeyStokes off to the JTextArea before the JFrame KeyListener sees them. Change the ta to this on line 14 and you will see no more KeyEvents.
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class TestKey extends JFrame
Container cp;
JTextArea ta;
TestKey()
cp = getContentPane();
ta = new JTextArea(20,80);
ta.addKeyListener(new java.awt.event.KeyAdapter()
public void keyPressed(KeyEvent e)
main_keyPressed(e);
cp.add(ta,BorderLayout.CENTER);
pack();
void main_keyPressed(KeyEvent e)
System.out.println(e);
static public void main(String[] args)
TestKey tk;
tk = new TestKey();
tk.show(); -
KeyListener - how to handle series of key pressed
Hi,
Is there a way to handle a series of key pressed in the keyPressed(KeyEvent e) method. for instance, I want to popup a dialogbox when the user pressed: F9, 31, F9 ?
thanks,
chauIs there a way to handle a series of key pressed in
the keyPressed(KeyEvent e) method. for instance, I
want to popup a dialogbox when the user pressed: F9,
31, F9 ?Look at the following.
import java.awt.event.*;
import javax.swing.*;
/* http://forum.java.sun.com/thread.jspa?messageID=2900727 */
/* http://forums.devshed.com/t218618/s.html */
class KeyListenerDemo {
public static void main(String[] args) {
new KeyListenerDemo().go();
void go() {
JTextField field = new JTextField("Press a key, and watch the console.");
field.setEditable(false);
field.addKeyListener(new MyKeyListener());
JFrame frame = new JFrame("KeyListener Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(field);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
class MyKeyListener extends KeyAdapter {
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ESCAPE) System.exit(0);
System.out.println("Typed: " + e.getKeyChar());
}It shouldn't take too much imagination to figure out how to make the listener listen for that combination.... -
Problem using KeyListener in a JFrame
Let's see if anyone can help me:
I'm programming a Maze game, so I use a JFrame called Window, who extends JFrame and implements ActionListener, KeyListener. Thw thing is that the clase Maze is a JPanel, so I add it to my Frame and add the KeyListener to both, the Maze and the Window, but still nothing seems to happen.
I've tried to remove the KeyListener from both separately, but still doesn't work...
Any suggestions???This is the code for my Window.java file. May be someone can see the error...
package maze;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Window extends JFrame implements ActionListener, KeyListener {
private Maze maze;
private JButton crear = new JButton("New");
public Window(int size, String s) {
super("3D Maze");
boolean b = true;
if (s.equalsIgnoreCase("-n"))
b = false;
else if (s.equalsIgnoreCase("-v"))
b = true;
Container c = getContentPane();
c.setLayout(new BorderLayout());
maze = new Maze(size,size,b);
crear.addActionListener(this);
addKeyListener(this);
maze.addKeyListener(this);
c.add(crear,BorderLayout.NORTH);
c.add(maze,BorderLayout.CENTER);
setSize(600,650);
show();
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == e.VK_UP || e.getKeyCode() == e.VK_W)
maze.walk();
else if (e.getKeyCode() == e.VK_DOWN || e.getKeyCode() == e.VK_S)
maze.back();
else if (e.getKeyCode() == e.VK_LEFT || e.getKeyCode() == e.VK_A)
maze.turnLeft();
else if (e.getKeyCode() == e.VK_RIGHT || e.getKeyCode() == e.VK_D)
maze.turnRight();
else if (e.getKeyCode() == e.VK_V)
maze.alternaMostrarCreacion();
else if (e.getKeyCode() == e.VK_M)
maze.switchMap();
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {
public void actionPerformed(ActionEvent e) {
maze.constructMaze();
public static void main(String[] args) {
int i = 30;
String s = "-v";
if (args.length != 0) {
try {
i = Integer.parseInt(args[0]);
if (!(i >= 15 && i <= 50))
i = 30;
s = args[1];
catch(Exception e) {}
Window w = new Window(i,s);
w.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
ImageIcon im = new ImageIcon("./Logo.gif");
String s = "";
s += "3D MAZE\n\n";
s += "Creator: Allan Marin\n";
s += "http://metallan.topcities.com\n\n";
s += ""+((char)(169))+" 2002";
JOptionPane.showMessageDialog(null,s,"About...",JOptionPane.PLAIN_MESSAGE,im);
System.exit(0);
} -
JButton keeps JFrame from succesfully implementing KeyListener?!
Look at this code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Test extends JFrame implements KeyListener
private JButton myButton;
public Test()
Container c = getContentPane();
c.setLayout( new FlowLayout() );
myButton = new JButton();
myButton.setEnabled( true );
c.add( myButton );
addKeyListener( this );
setSize( 100, 100 );
show();
public void keyPressed( KeyEvent e )
System.out.println( "keyPressed" );
public void keyReleased( KeyEvent e )
System.out.println( "keyReleased" );
public void keyTyped( KeyEvent e )
System.out.println( "keyTyped" );
public static void main( String args[] )
Test window = new Test();
}When you execute this program, the JFrame does not resolve keystrokes. It should though, because it implements KeyListener and overrides all required methods. But here is the strange thing: Try changing
myButton.setEnabled( true );to
myButton.setEnabled( false );Now the JFrame is able to respond to keystrokes by executing the proper methods! But what use is a button if it is not enabled. I need my buttons in the JFrame, but I also need the JFrame to respond to the keystrokes.
Anyone know about this problem and how to solve it??
Thank you!?? Say you want to make a small game. A square is drawn onto the frame. The user presses the up button on the keybord and the square 'moves' up (it is repainted at a different coordinate). But the user also needs to be able to (re)start the game and exit through the use of JButtons. That is the purpose and the problem is stated in my first post...
Anyone else has an idea?
thx -
I searched through this forum trying to figure out how to make a KeyListener work for an entire JFrame, but could not understand the answers all you java experts out there gave... Could someone please simplify it for me by explaining your code instead of just typing it in and saying "that's how you do it"? Because I really didn't get what to do. I have a class that implements a KeyListener and extends the JFrame I want the KeyListener for. I tried a simple "addKeyListener(this)" but the events for the Listener were never triggered. I would be very thankful for any and all responses given.
The following simple program
import javax.swing.*;
import java.awt.event.*;
public class KeyListenerTest {
public static void main(String[] args) {
KeyListenerFrame frame = new KeyListenerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(frame);
frame.show();
class KeyListenerFrame extends JFrame implements KeyListener {
public void keyPressed(KeyEvent evt) {
System.out.println("keyPressed");
public void keyReleased(KeyEvent evt) {
System.out.println("keyReleased");
public void keyTyped(KeyEvent evt) {
System.out.println("keyTyped");
}opens a JFrame which triggers all of the three handled events whenever a key is pressed on the keyboard.
I am not sure whether this is could be an answer to your problem or rather I missed the point...
Bye -
How to add a KeyListener for the JFrame (when I'm typing in a JTextField)?
I have some problem with KeyListener..
I add a KeyListener (I named it "listener") for my JFrame and it works fine. Then I add JTextField to the JFrame. When I'm typing some text in the JTextField - my "listener" does not work. (cause my JTextField doesn't have a KeyListener).
I just want to make an ability to process hot keys which user presses in my java program..
Does anyone know how to do it?In future, please ask Swing questions in the [Swing Forum.|http://forums.sun.com/forum.jspa?forumID=57]
Don't use KeyListener. In fact KeyListener is seldom useful. Use key binding: [http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html]
Or you can have menu items with accelerators (hot keys). -
Global KeyListener in JFrame with JDK 1.4
Hi!
I need to get some keyboard events in my JFrame or JDialog, no matter what subcomponent currently has the focus. I use this for example to display a help screen when the user hits F1.
In JDK 1.3 I wrote in my constructor:
this.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(KeyEvent e) {
this_keyPressed(e);
and then had a method
void this_keyPressed(KeyEvent e) { ... }
handling those events.
In JDK 1.4 this code only works, if I call this.requestFocus(), but since the user should be able to TAB through the frame and hit F1 in every textfield, button etc., this is no solution --- as soon as "this" loses the focus, it won't work any more.
I also tried using Key Bindings, but somehow I couldn't get it working.
I need a solution for this problem that works with 1.3 as well as with 1.4!! Do you have any ideas of how to do this?
Thanks for your help!!
Nicolas Michael <[email protected]>looking at the source for Choice its not doing a great deal in add():
pItems is a vector, so I guess if there is anything that could be slow its the native call, but again this seems unlikely?
btw, if ur adding to the Choice box when its visible it will be a lot slower - is it possible to initialise before the applet is displayed?
asjf
ps. note the demo code above is adding numbers as strings, but I agree this shouldn't make any difference
//from java/awt/Choice.java (same from 1.2.1 to 1.4.1 - have not checked 1.1)
public void add(String item) {
addItem(item);
public void addItem(String item) {
synchronized (this) {
addItemNoInvalidate(item);
if (valid)
invalidate();
private void addItemNoInvalidate(String item) {
if (item == null) {
throw new
NullPointerException("cannot add null item to Choice");
pItems.addElement(item);
ChoicePeer peer = (ChoicePeer)this.peer;
if (peer != null) {
peer.addItem(item, pItems.size() - 1);
if (selectedIndex < 0) {
select(0);
} -
Problem with backspace on JFrame
Hello,
I have a problem on a JFrame. Indeed, I add a keyListener to the frame, but the "Bakcspace" don't work. There is anything when a I press on Backspace (with KeyTyped, KeyReleased and KeyPressed). All other keys are working.
Thanks.the solution of the problem is :
Version note: This page reflects the focus API introduced in released 1.4. As of that release, the focus subsystem consumes focus traversal keys, such as Tab and Shift Tab. If you need to prevent the focus traversal keys from being consumed, you can call
component.setFocusTraversalKeysEnabled(false)
on the component that is firing the key events. Your program must then handle focus traversal on its own. Alternatively, you can use a KeyEventDispatcher to pre-listen to all key events. The focus page (in the Creating a GUI with JFC/Swing trail) has detailed information on the focus subsystem. -
Advance level drawing problem with Jframe and JPanel need optimize sol?
Dear Experts,
I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
Note: i don't want to inherit jpanel or Jframe
here is my code : import java.awt.BorderLayout;
public class GameMain extends JFrame {
private static final long serialVersionUID = 1L;
public int mX, mY;
int localpoints = 0;
protected static JTextField[][] squares;
protected JLabel statusLabel = new JLabel("jugno");
Label lbl_score = new Label("score");
Label lbl_scorelocal = new Label("local score");
protected static TTTService remoteTTTBoard;
// Define constants for the game
static final int CANVAS_WIDTH = 800; // width and height of the game screen
static final int CANVAS_HEIGHT = 600;
static final int UPDATE_RATE = 4; // number of game update per second
static State state; // current state of the game
private int mState;
// Handle for the custom drawing panel
private GameCanvas canvas;
// Constructor to initialize the UI components and game objects
public GameMain() {
// Initialize the game objects
gameInit();
// UI components
canvas = new GameCanvas();
canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
this.setContentPane(canvas);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.pack();
this.setTitle("MY GAME");
this.setVisible(true);
public void gameInit() {
// Shutdown the game, clean up code that runs only once.
public void gameShutdown() {
// To start and re-start the game.
public void gameStart() {
private void gameLoop() {
public void keyPressed(KeyEvent e) {
public void keyTyped(KeyEvent e) {
public void gameKeyReleased(KeyEvent e) {
PuzzleBoard bd = getBoard();
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 4; ++col) {
if (e.getSource() == squares[row][col]) {
if (bd.isOpen(col, row)) {
lbl_score.setText("Highest Score = "
+ Integer.toString(bd.getPoints()));
setStatus1(bd);
pickSquare1(col, row, squares[row][col].getText()
.charAt(0));
protected void pickSquare1(int col, int row, char c) {
try {
remoteTTTBoard.pick(col, row, c);
} catch (RemoteException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
System.exit(1);
// method "called" by remote object to update the state of the game
public void updateBoard(PuzzleBoard new_board) throws RemoteException {
String s1;
for (int row = 0; row < 4; ++row) {
for (int col = 0; col < 4; ++col) {
squares[row][col].setText(new_board.ownerStr(col, row));
lbl_score.setText("Highest Score = "
+ Integer.toString(new_board.getPoints()));
setStatus1(new_board);
protected void setStatus1(PuzzleBoard bd) {
boolean locals = bd.getHave_winner();
System.out.println("local win" + locals);
if (locals == true) {
localpoints++;
System.out.println("in condition " + locals);
lbl_scorelocal.setText("Your Score = " + localpoints);
lbl_score
.setText("Highest Score = " + Integer.toString(bd.getPoints()));
protected PuzzleBoard getBoard() {
PuzzleBoard res = null;
try {
res = remoteTTTBoard.getState();
} catch (RemoteException e) {
System.out.println("Exception: " + e.getMessage());
e.printStackTrace();
System.exit(1);
return res;
/** Custom drawing panel (designed as an inner class). */
class GameCanvas extends JPanel implements KeyListener {
/** Custom drawing codes */
@Override
public void paintComponent(Graphics g) {
// setOpaque(false);
super.paintComponent(g);
// main box; everything placed in this
// JPanel box = new JPanel();
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
// add(statusLabel, BorderLayout.NORTH);
// set up the x's and o's
JPanel xs_and_os = new JPanel();
xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
squares = new JTextField[5][5];
for (int row = 0; row < 5; ++row) {
for (int col = 0; col < 5; ++col) {
squares[row][col] = new JTextField(1);
squares[row][col].addKeyListener(this);
if ((row == 0 && col == 1) || (row == 2 && col == 3)
|| (row == 1 && col == 4) || (row == 4 && col == 4)
|| (row == 4 && col == 0))
JPanel p = new JPanel(new BorderLayout());
JLabel label;
if (row == 0 && col == 1) {
label = new JLabel("1");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 4 && col == 0) {// for two numbers or
// two
// blank box in on row
label = new JLabel("2");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 1 && col == 4) {
label = new JLabel("3");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else if (row == 4) {
label = new JLabel("4");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
else {
label = new JLabel("5");
label.setHorizontalAlignment(JLabel.LEFT);
label.setVerticalAlignment(JLabel.TOP);
label.setOpaque(true);
label.setBackground(squares[row][col].getBackground());
label.setPreferredSize(new Dimension(label
.getPreferredSize().width, squares[row][col]
.getPreferredSize().height));
p.setBorder(squares[row][col].getBorder());
squares[row][col].setBorder(null);
p.add(label, BorderLayout.WEST);
p.add(squares[row][col], BorderLayout.CENTER);
xs_and_os.add(p);
} else if ((row == 2 && col == 1) || (row == 1 && col == 2)
|| (row == 3 && col == 3) || (row == 0 && col == 3)) {
xs_and_os.add(squares[row][col]);
// board[ row ][ col ].setEditable(false);
// board[ row ][ col ].setText("");
squares[row][col].setBackground(Color.RED);
squares[row][col].addKeyListener(this);
} else {
squares[row][col] = new JTextField(1);
// squares[row][col].addActionListener(this);
squares[row][col].addKeyListener(this);
xs_and_os.add(squares[row][col]);
this.add(xs_and_os);
this.add(statusLabel);
this.add(lbl_score);
this.add(lbl_scorelocal);
public void keyPressed(KeyEvent e) {
public void keyReleased(KeyEvent e) {
gameKeyReleased(e);
public void keyTyped(KeyEvent e) {
// main
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new GameMain();
thanks a lot for your time , consideration and efforts.
jibby
Edited by: jibbylala on Sep 20, 2010 6:06 PMjibbylala wrote:
thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well. -
Trouble with focus, swing & keyListener
can anybody out there help me with this problem, I got stuck with:
I create a JDialog in a JFrame & would like to add Keylistener to the JDialog as soon as it opens..........but the it doesn't seem to be working....Oops! As bbhangale pointed out, my previous post is incorrect. It should read as follows:
dialog.getRootPane().getInputMap...
dialog.getRootPane().getActionMap...Actually, I've created MyDialog, an abstract sub-class of JDialog. In it, I over-ride the createRootPane() method and delcare the abstract onDialogClose() method. Here's what that looks like:
public abstract class MyDialog extends JDialog
// Implement MyDialog wrappers for all the JDialog constructors
public MyDialog()
super();
* Overriding this method to register an action so the 'Esc' key will dismiss
* the dialog.
* @return a <code>JRootPane</code> with the appropiate action registered
protected JRootPane createRootPane()
JRootPane rootPane = new JRootPane();
rootPane.getInputMap( JComponent.WHEN_IN_FOCUSED_WINDOW ).
put( KeyStroke.getKeyStroke( KeyEvent.VK_ESCAPE, 0 ), "escPressed" );
rootPane.getActionMap().
put( "escPressed", new AbstractAction( "escPressed" )
public void actionPerformed( ActionEvent actionEvent )
onDialogClose();
return rootPane;
* This method gets called when the user attemps to close the JDialog via the
* 'Esc' key. It is up to the sub-class to implement this method and handle
* the situation appropriately.
protected abstract void onDialogClose();
}Then, anytime I need a dialog, I sub-class MyDialog and implement onDialogClose() to do whatever I want it to do when the user presses 'Esc'.
I swear I've been using it for quite some time now and it works beautifully!
Jamie -
KeyListener no longer working in JPanel
Hi,
I have implemented a graphics interface with JPanel with mouse action and movement captured. Everything works fine until I added KeyListener implementation.
No matter what I do, I could not enable the key event.
The top window is a JFrame which contains several components and one of them is a JPanel. I wanted to capture key event inside that JPanel.
JFrameC a = new JFrameC();
JPanelC b = new JPanelC(a);
And inside JPanelC, I have statement as
a.addKeyListener(this);
addKeyListener(this);
But still no key event.
If I simply change JPanelC class from JPanel to Panel (only extends statement), key event appears as it supposes to be.
What's wrong with JPanel? I thought it should behave similar to Panel with more better features.
What should I do to enable key event in JPanel?
Please help.I tried the following simple program which is similar to my complicated implementation and it worked. I am confused.
<pre>
//KeyFrame.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.*;
public class KeyFrame extends JFrame {
public KeyFrame(String s) {
super(s);
KeyEventDemo ked = new KeyEventDemo(this);
getContentPane().add(ked);
pack();
show();
setSize(500, 500);
validate();
public static void main(String [] args) {
KeyFrame kf = new KeyFrame("");
// KeyEventDemo.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.BorderLayout;
import java.awt.*;
public class KeyEventDemo extends JPanel
//implements KeyListener, ActionListener {
implements KeyListener {
public KeyEventDemo(Component c) {
super();
c.addKeyListener(this);
//addKeyListener(this);
/** Handle the key typed event from the text field. */
public void keyTyped(KeyEvent e) {
System.err.println("KEY TYPED: ");
/** Handle the key pressed event from the text field. */
public void keyPressed(KeyEvent e) {
System.err.println("KEY PRESSED: ");
/** Handle the key released event from the text field. */
public void keyReleased(KeyEvent e) {
System.err.println("KEY RELEASED: ");
</pre> -
Resizing JFrame on button click to show an image on the JFrame
Dear All,
I have a JFrame which has an empty label. On button click I want to set an icon for the label and want the JFrame to be resized to show that icon. I am using frame.pack() and I am not using any other sizing function. The code that I have right now, prints the image on the panel, but does not resize the frame to show the image. Pleae could someone help.package gui;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class ComponentDemo extends JPanel implements ActionListener,
ItemListener, MouseListener, KeyListener {
private JTextArea textarea;
private JButton button;
private final static String newline = "\n";
private JLabel imageIcon;
public ComponentDemo() {
button = new JButton("JButton welcomes you to CO2001");
button.addActionListener(this);
add(button);
textarea = new JTextArea(10, 50);
textarea.setEditable(false);
addMouseListener(this);
textarea.addKeyListener(this);
JScrollPane scrollPane = new JScrollPane(textarea);
add(scrollPane);
imageIcon = new JLabel();
add(imageIcon);
setBackground(Color.pink);
new JScrollPane(this);
* Create the GUI and show it. For thread safety, this method should be
* invoked from the event-dispatching thread.
private static void createAndShowGUI() {
// Create and set up the window.
JFrame frame = new JFrame("Simple FrameDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(700, 200);
// get the content pane and set the background colour;
frame.add(new ComponentDemo());
// frame.setSize(screenSize);
// frame.getContentPane().setBackground(Color.cyan);
// Display the window.
frame.pack();
frame.setVisible(true);
frame.setResizable(true);
public static void main(String[] args) {
// Schedule a job for the event-dispatching thread:
// creating and showing this application's GUI.
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (e.getSource() instanceof JButton) {
// System.out.println(e.getSource());
String text = ((JButton) e.getSource()).getText();
textarea.append(text + newline);
textarea.setBackground(Color.cyan);
textarea.setForeground(Color.BLUE);
textarea.setCaretPosition(textarea.getDocument().getLength());
imageIcon.setIcon(createImageIcon("SwingingDuke.png",
"Image to be displayed"));
@Override
public void itemStateChanged(ItemEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseClicked(MouseEvent arg0) {
textarea.append("A Mouse click welcomes you to CO2001" + newline);
textarea.setBackground(Color.green);
textarea.setCaretPosition(textarea.getDocument().getLength());
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
@Override
public void keyPressed(KeyEvent e) {
System.out.println(e.getKeyChar());
textarea.append("The key " + e.getKeyChar()
+ " click welcomes you to CO2001" + newline);
textarea.setBackground(Color.YELLOW);
textarea.setFont(new Font("Arial", Font.ITALIC, 16));
textarea.setCaretPosition(textarea.getDocument().getLength());
@Override
public void keyReleased(KeyEvent e) {
System.out.println(e.getKeyChar());
// textarea.append("The key "+
// e.getKeyChar()+" click welcomes you to CO2001" + newline);
// textarea.setBackground(Color.green);
// textarea.setCaretPosition(textarea.getDocument().getLength());
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
System.out.println(e.getKeyChar());
// textarea.append("The key "+
// e.getKeyChar()+" click welcomes you to CO2001" + newline);
// textarea.setBackground(Color.blue);
// textarea.setCaretPosition(textarea.getDocument().getLength());
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path, String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
System.out.println("found");
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}myJPanel.setPerferredSize(new Dimension(new_width, new_hight));
myJFrame.pack(); -
hello all,
i was doing this homework, and i came upon a point a cant really do. well here is the code:
package homework;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class Draw1 extends JFrame implements MouseMotionListener
private JRadioButton boldRadio,plainRadio,italicRadio;
private JTextField textField;
private Font boldFont, plainFont, italicFont;
private JComboBox box1;
private String CB[] = {"Red","Green","Text"};
private Color ovalColor= Color.RED;
private String X="";
public Draw1()
this.addMouseMotionListener(this);
Container c=this.getContentPane();
JPanel p= new JPanel(new FlowLayout());
boldFont=new Font("Serif" ,Font.BOLD,14);
plainFont=new Font("Serif" ,Font.PLAIN,14);
italicFont=new Font("Serif" ,Font.ITALIC,14);
textField= new JTextField();
textField.setFont( boldFont );
box1 = new JComboBox(CB);
box1.setMaximumRowCount(1);
box1.addItemListener(
new ItemListener(){
public void itemStateChanged(ItemEvent event2){
if(event2.getStateChange() == ItemEvent.SELECTED)
if(box1.getSelectedIndex() == 0)
ovalColor= Color.RED;
else if(box1.getSelectedIndex() == 1)
ovalColor= Color.GREEN;
//else if(box1.getSelectedIndex() == 2)
boldRadio=new JRadioButton("Bold",true);
plainRadio=new JRadioButton("Plain",false);
italicRadio=new JRadioButton("Italic",false);
RadioButtonHandler handler = new RadioButtonHandler();
boldRadio.addItemListener(handler);
plainRadio.addItemListener(handler);
italicRadio.addItemListener(handler);
ButtonGroup radioGroup=new ButtonGroup();
radioGroup.add(boldRadio);
radioGroup.add(plainRadio);
radioGroup.add(italicRadio);
p.add(box1);
p.add(boldRadio);
p.add(plainRadio);
p.add(italicRadio);
c.add(p,BorderLayout.NORTH);
c.add(textField,BorderLayout.SOUTH);
c.setBackground(Color.white);
this.setSize(300,300);
this.setVisible(true);
public static void main(String[] args)
Draw1 draw11 = new Draw1();
public void mouseDragged(MouseEvent e)
Graphics g=this.getGraphics();
g.setColor(ovalColor);
g.fillOval(e.getX(),e.getY(),20,20);
public void mouseMoved(MouseEvent e)
//TODO: implement this java.awt.event.MouseMotionListener method;
private class RadioButtonHandler implements ItemListener {
public void itemStateChanged( ItemEvent event )
if ( event.getSource() == boldRadio )
textField.setFont( boldFont );
else if ( event.getSource() == plainRadio )
textField.setFont( plainFont );
else if ( event.getSource() == italicRadio )
textField.setFont( italicFont );
}what i need is to add a keylistener, that would be activated when i select "text" from the combobox, and when this listener is active, anything i type should go into the textfield. even if i dont click the textfield.import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test extends JFrame implements MouseMotionListener {
FieldKeyListener fieldKeyListener = new FieldKeyListener();
private JRadioButton boldRadio,plainRadio,italicRadio;
private JTextField textField;
private Font boldFont, plainFont, italicFont;
private JComboBox box1;
private String CB[] = {"Red","Green","Text"};
private Color ovalColor= Color.RED;
private String X="";
private boolean keyListenerIsActive = false;
int count = 0;
public test() {
this.addMouseMotionListener(this);
Container c=this.getContentPane();
JPanel p= new JPanel(new FlowLayout());
boldFont=new Font("Serif" ,Font.BOLD,14);
plainFont=new Font("Serif" ,Font.PLAIN,14);
italicFont=new Font("Serif" ,Font.ITALIC,14);
textField= new JTextField();
textField.setFont( boldFont );
textField.addKeyListener(fieldKeyListener);
box1 = new JComboBox(CB);
box1.setMaximumRowCount(1);
box1.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent event2){
//System.out.println("stateChange" +
// event2.getStateChange());
if(event2.getStateChange() == ItemEvent.SELECTED)
if(box1.getSelectedIndex() == 0) {
ovalColor= Color.RED;
keyListenerIsActive = false;
else if(box1.getSelectedIndex() == 1) {
ovalColor= Color.GREEN;
keyListenerIsActive = false;
else if(box1.getSelectedIndex() == 2) {
// toggle the key listener control boolean
keyListenerIsActive = !keyListenerIsActive;
textField.requestFocus(true);
count = 0;
System.out.println("keyListenerIsActive = " +
keyListenerIsActive);
boldRadio=new JRadioButton("Bold",true);
plainRadio=new JRadioButton("Plain",false);
italicRadio=new JRadioButton("Italic",false);
RadioButtonHandler handler = new RadioButtonHandler();
boldRadio.addItemListener(handler);
plainRadio.addItemListener(handler);
italicRadio.addItemListener(handler);
ButtonGroup radioGroup=new ButtonGroup();
radioGroup.add(boldRadio);
radioGroup.add(plainRadio);
radioGroup.add(italicRadio);
p.add(box1);
p.add(boldRadio);
p.add(plainRadio);
p.add(italicRadio);
c.add(p,BorderLayout.NORTH);
c.add(textField,BorderLayout.SOUTH);
c.setBackground(Color.white);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(400,200);
this.setSize(300,300);
this.setVisible(true);
public void mouseDragged(MouseEvent e)
Graphics g=this.getGraphics();
g.setColor(ovalColor);
g.fillOval(e.getX(),e.getY(),20,20);
public void mouseMoved(MouseEvent e)
//TODO: implement this java.awt.event.MouseMotionListener method;
private class RadioButtonHandler implements ItemListener {
public void itemStateChanged( ItemEvent event )
if ( event.getSource() == boldRadio )
textField.setFont( boldFont );
else if ( event.getSource() == plainRadio )
textField.setFont( plainFont );
else if ( event.getSource() == italicRadio )
textField.setFont( italicFont );
class FieldKeyListener implements KeyListener {
public void keyPressed(KeyEvent e) {
if(!keyListenerIsActive)
return;
System.out.println("keyPressed " + count++);
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { }
public static void main(String[] args) {
new test();
} -
I writing a calculator and I use both JButton & keyboard as inputs. The ActionListener with the JButtons is ok, but I have problem with keyboard:
I have and object 'keylistener' of a class that implements KeyListener and I addKeyListener(keylistener) for all the JButton. But when i start the application, nothing happens when I press anykey, the KeyListener only works after I use mouse to lick to any JButton, and then I can use the keyboard.
I have many JButton and I group them into JPanels. I tried to addKeyListener(keylistener) for all the JPanels but it did not work, too.
I think my problem is that no JButton is focused at the beginning. But I don't know how to set a button focused. I tried with requestFocus... methods but they did not help.
What I have to do now? Please help!!!
Thank you very much!KeyListener is seldom the answer for input tasks. Instead use key binding (InputMap/ActionMap):
http://java.sun.com/products/jfc/tsc/special_report/kestrel/keybindings.html
Demo:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonExample2 extends AbstractAction implements Runnable {
public void run() { //build GUI in EDT
Toolkit.getDefaultToolkit().setLockingKeyState(KeyEvent.VK_NUM_LOCK, true);
JPanel panel = new JPanel(new GridLayout(3,3));
InputMap im = panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = panel.getActionMap();
for(int i=1; i<10; ++i) {
String text = String.valueOf(i);
JButton btn = new JButton(text);
btn.addActionListener(this);
panel.add(btn);
//set up action
String key = "press" + text;
im.put(KeyStroke.getKeyStroke(text), key); //main keyboard
im.put(KeyStroke.getKeyStroke("NUMPAD" + text), key); //numpad
am.put(key, this);
JFrame f = new JFrame("ButtonExample2");
f.setContentPane(panel);
f.pack();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
public void actionPerformed(ActionEvent evt) {
System.out.println("Pressed: " + evt.getActionCommand());
public static void main(String[] args) {
EventQueue.invokeLater(new ButtonExample2());
}
Maybe you are looking for
-
Linking parameters in a subreport
Hello All, How do i link parameters in a sub report. I have 2 subreports and I have to link them with cascading dynamic parameters For the first sub report I an using 1st level of the parameter and for second report I am using 2 level of the dynamic
-
ITunes and iPod aren't working correctly
So, I go and buy my new laptop today, with hopes of loading all my music that I backed up onto 4 DVDs. I go to load my music from the DVDs and they don't work. Whatever. So I go and follow Apple's instructions on how to backup my library on my iPod,
-
When I turn my Mac off it restarts since I installed Snow Leopard 10.6.3 - Help
Hello, I recently installed SL 10.6.3 and since, I ca't turn my computor off... it restarts, I have tu unplug it. I phoned support but they say it's my computor, not the software. However, on checking on the net, it seems I'm not the only person with
-
My nano says connected eject before disconnecting what does that mean
I plugged my new iPod nano in a couple hours ago and it says "connected eject before disconnecting" what does that mean?
-
TS2972 How come when I do the homesharing quite a bit of my library is missing?
Many of the songs in my homeshared library are missing. Why is this?