Add a KeyListener to JTextField

Hello:
I got some questions to ask you.
1) How to add a KeyListener to a JTextField, and I'd like to known how
to use System.out.println to print out the values which are from keyBoard?
2) How to put the JTextField in the middle of the JFrame?
import javax.swing.*;
import java.awt.*;
public class TestKeyListener extends JFrame{
     private static TestKeyListener tKL;
     private static JTextField jTF;
     private static Container c;
     private static GridLayout gL;
     public static void main(String [] args){
          tKL=new TestKeyListener();
          tKL.setVisible(true);
     public TestKeyListener(){
          setSize(400,400);
          setTitle("TestKeyListener");
          jTF=new JTextField();
          gL=new GridLayout(10,1);
          c=getContentPane();
          c.setLayout(gL);
          setUp();
     private void setUp(){
     c.add(jTF);

hello,
try this
1) jTF.addKeyListener (new KeyListener ()
public void keyPressed (KeyEvent keye)
// your other codes goes here
// to print out the text in the textfield see code below
String printout = jTF.getText();
System.out.println (printout);
Note: there are more methods of the KeyListener such as keyReleased e.t.c pls bwrosed through the documentation for the jdk version u are using to get more of those methods.
2) u can simply use borderlayout to add the textfield to the center of the frame
frame.getContentPane().add (jTF, BorderLayout.CENTER);
of if it is an awt frame
frame.add(jTF, BorderLayout.CENTER);
Note that ActionListener works for JTextFields as well by pressing the enter key on your keyboard.
I hope this helps
Cheers

Similar Messages

  • 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).

  • How to add a KeyListener to a JInternalFrame

    1). I have Main Window which is an Application window and has a menu. When I click on a menu option,
    a user interface which is a JInternalFrame type, with JTextFields in it, is loaded.
    2). In the first JTextField(e.g. Employee Number), I have a KeyListener added to the JInternalFrame.
    3). When I enter an Employee number in the JTextField and press the Key F10, I have to fetch the details about the Employee
    (his first name, middle name, last name etc.) from the database and display these details in the corresponding
    JTextFields in the user interface.
    PROBLEM:
    I am able to add a KeyListener to the JInternalFrame but it does not work the way I need it to.
    The moment F10 key is pressed, the JInternalFrame looses focus, and the focus goes to the Main Window and does not execute
    the code for the keyPressed event that is there in the listener.
    How do I overcome this issue??
    The code that I am using is below
    public class TD {
    public void invoke(){
    cFrame = new JInternalFrame("TD Form",
    false, //resizable
    true, //closable
    true, //maximizable
    true);//iconifiable
    // More code here..................
    //Destroy the TD Window.
    cFrame.addInternalFrameListener(new InternalFrameAdapter() {
         public void internalFrameClosing(InternalFrameEvent evt){
                   cancelSteps();
    }); // end of InternalFrameListener.
    cFrame.addKeyListener(new KeyTD(this)); // Adding the KeyListener here to the JInternalFrame
    cFrame.setVisible(true);
    cFrame.setSize(800,450);
    cFrame.setLocation(10,10);
    } // end of the constructor.
    // Inner class that implements the KeyListener
    class KeyTD implements KeyListener {
    private int msg =JOptionPane.INFORMATION_MESSAGE;
    private String title = "KeyPress Event Message";
    Container cornbut;
    TD objTD;
    private int UTNum;
    public KeyTD(TD objTD){
              this.objTD = objTD;
    public void keyPressed(KeyEvent ke){
    int key1 = ke.getKeyCode();
    switch(key1){
    case KeyEvent.VK_F9:
    tD_F9();
    break;
    case KeyEvent.VK_F10:
    UTNum = getNum(); // Reads the content of the JTextField and gets the Integer value
    if (UTNum > 0){
                        tD_F10();
    }else{
    JOptionPane.showMessageDialog(cornbut," Please enter the Number. ",title,msg);
    break;
    }//end of keyPressed method
    public void keyReleased(KeyEvent ke){
    public void keyTyped(KeyEvent ke){
    public void tD_F9(){
    //sets focus to the Text Field where the key listener has been added
    }//end of tD_F9 method
    public void tD_F10(){
    String str = String.valueOf(UTNum);
    Objdbdef.fetchTaskDefiner(str,"", "","" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" ,"" );
    if(//there are records in the database then){                       
    // If there are records matching the number from the JTextField the display statements are here.........
    }else{
    JOptionPane.showMessageDialog(cornbut,"There are no records found for the specified criteria.",title,msg);
    }//end of td_F10 method
    }// end of KeyTD class

    As a rule of thumb, I never use KeyListeners, unless you want to listen to many different key strokes.
    Instead, use ActionMap/InputMap. You can attach an action to, say your desktop, that
    is activated when F1 is pressed WHEN_ANCESTOR_OF_FOCUSED_COMPONENT or
    WHEN_IN_FOCUSED_WINDOW

  • How to add words from a JTextField to a JList

    Im working on my final project for Java programming class using JApplet.
    Im trying to create a spelling test/wordfind
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.
    then click the "Start" Button and have the all the words from the JList be put in random stops in a panel and fill around all the words with random letters.
    then when the user clicks on the letter of the words they are finding it will change colors if they click on it again it will change back to its original color.
    So far I have my layout set up its adding the proper Listeners and events to achieve the desired results.
    I know this is way more advanced than what My Instructor is even teacher but I am very interested in Java and want to learn a lot more about it.
    If anyone has suggestions or know where i can find the information Im looking for please let me know.
    Thanks
    Code I have so Far:
    * @(#)SpellingTest.java
    * SpellingTest Applet application
    * @author
    * @version 1.00 2010/11/10
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class SpellingTest extends JApplet implements ActionListener {
         Image img;
         ImageIcon icon;
         private Image title;
         JTextField word;
         JButton addWord;
         JLabel label;
         JList wordList;
         public void init() {//opening init
                   getContentPane().setLayout(null);
                   getContentPane().setBackground(Color.WHITE);
                   title = getImage(getDocumentBase(), "title.jpg");
                   //The text field
                   word = new JTextField();
                   word.setLocation(190,100);
                   word.setSize(85,30);
                   getContentPane().add(word);
                   word.addActionListener(this);
                   //The addWord button
                   addWord = new JButton("ADD");
                   addWord.setLocation(295, 100);
                   addWord.setSize(90,30);
                   getContentPane().add(addWord);
                   addWord.setBackground(new Color(146, 205, 220));
                   addWord.addActionListener(this);
                   //The label
                   label = new JLabel("Type your spelling words:");
                   label.setLocation(25, 65);
                   label.setSize(250,100);
                   getContentPane().add(label);
                   label.setForeground(new Color(146, 205, 220));
                   //The List
                   wordList = new JList();
                   JScrollPane scrollPane = new JScrollPane(wordList,
                   ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
                   ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
                   scrollPane.setLocation(25,150);
                   scrollPane.setSize(150,300);
                   getContentPane().add(scrollPane);
         }//closing init
         public void actionPerformed (ActionEvent ae){
              Object obj = ae.getSource();
              String text = word.getText();
              if (obj == addWord){
                   if (text.length()>0);
                   wordList.addString("");
         public void paint(Graphics g) {
              super.paint(g);
    }

    Read the first posting titled "Welcome to the new home" to learn how to use code tags. Then you can edit your posting so the code is formatted and readable.
    I want to be able to have the user type a word in the JtextField press the "Add" button (Jbutton) and have the word be added to the JList.Read the JList API and follow the link to the Swing tutoral on "How to Use Lists" where you will find a working example.
    So far I have my layout Actually you haven't. You should learn how to use layout managers. Again the Swing tutorial explains what layout managers are and provides working example of using them.
    I am very interested in Java and want to learn a lot more about it.A great place to start is by read tutorials because they always contain working example. Here are some [url http://download.oracle.com/javase/tutorial/]Java tutorrial.

  • DefaultListModel  HELP =P  i need to add something to the JTextField

          add.addActionListener(addtext);
      }   // End of the constructor
    private JTextField boxlist = new JTextField();      <--  Box that is supose to show what do we add to the list.(Display the names)                  
    private JTextField boxname = new JTextField("type your name here...");   <--- We right something and add to the boxlist
    private JButton add = new JButton("ADD");
    private AddButton addtext = new AddButton(); 
    private DefaultListModel listmodel = new DefaultListModel(); 
    private class ADDButton implements ActionListener{
              public void actionPerformed(ActionEvent e ){
                   listmodel.addElement("something")   <--------- don't what to do we this handler, it is supose to give action to the Button (ADD)
         }thanks

    Swing related questions should be posted in the Swing forum.
    If I understand your question then you should read the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/list.html]How to Use Lists for an example that upates a list with the text entered in a text field.

  • Add event(keyListener) to JTable Cell default editor.

    I've got a form(Jdialog) with a Jtable on it.
    I've added a keyListener to the JButtons and Jtable so that, wherever the the focus IS, when I hit the "F7" key, it fills the Jtable from the database connection.
    It's working REALLY fine now but there is one small glitch.
    When I'm editing a cell, the keyListener event is not thrown. I supposed it's because the "DefaultCellEditor" does not throw the event.
    How can I add such a thing??
    I'm looking for something like :
    table.getDefaultEditor().addKeyListener
    but it does not exists.
    If it's not possible, is there a way to make the JDialog listen to all the keyListener events from its childs??(Mimics the JDK < 1.4)
    Thx

    Using key binding is better implementation.
    After you read the tutorial your next move is to google for it.
    http://www.google.com/search?hl=en&q=jtable+keybinding
    Second result brings you to camickr's example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=657819

  • Revalidate/validate + repaint to add a number of JTextFields

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class FIFO_MenuBar extends JMenuBar {
    String[] prgsItems = new String[] {"Start Simulation", "Reset", "Exit"};
    String[] typeItems = new String[] {"FCFS", "HRRN", "PR", "RR", "SJF", "SRTN"};
    public JTextField jTxF0[];
    int k = 0;
    public FIFO_MenuBar () {
    JMenu progress = new JMenu("Program to...");
    JMenu typemenu = new JMenu("Simulations Types");
    ActionListener listen = new ActionListener() {
    public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand() == "Start Simulation") {
    k = Integer.parseInt(JOptionPane.showInputDialog("Enter number of process"));
    jTxF0 = new JTextField[k];
    JPanel panel = new JPanel();
    for (int i = 0; i < jTxF0.length; i++) {
    jTxF0[i] = new JTextField(10);
    panel.add(jTxF0);
    for (int i = 0; i < prgsItems.length; i++) {
    JMenuItem item = new JMenuItem(prgsItems[i]);
    item.addActionListener(listen);
    //System.out.println(item.getActionCommand());
    progress.add(item);
    progress.insertSeparator(2);
    for (int j = 0; j < typeItems.length; j++) {
    JMenuItem item = new JMenuItem(typeItems[j]);
    item.addActionListener(listen);
    typemenu.add(item);
    typemenu.insertSeparator(1);
    typemenu.insertSeparator(5);
    JMenuItem item;
    add(progress);
    add(typemenu);
    public static void main(String s[]) {
    JFrame frame = new JFrame("CPU Simulation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setJMenuBar(new FIFO_MenuBar());
    frame.pack();
    frame.setVisible(true);
    No idea why it wouldn't create the number of JTextFields that I want when I go from "Program to..." --> "Start Simulatioin"...
    It just wouldn't add the JTextField for me...

    you generally don't want anything in main() except to kick off the program
    FIFO_MenuBar is a menuBar, so you don't want to be putting your frame code in there,
    best to just pass any needed references.
    here's your code split into 2 classes with the necessary reference passed to FIFO....
    see if you can follow what's happening
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    class FIFO_MenuBar extends JMenuBar {
      String[] prgsItems = new String[] {"Start Simulation", "Reset", "Exit"};
      String[] typeItems = new String[] {"FCFS", "HRRN", "PR", "RR", "SJF", "SRTN"};
      public JTextField jTxF0[];
      int k = 0;
      public FIFO_MenuBar (final JPanel panel) {
        JMenu progress = new JMenu("Program to...");
        JMenu typemenu = new JMenu("Simulations Types");
        ActionListener listen = new ActionListener() {
          public void actionPerformed(ActionEvent event) {
            if (event.getActionCommand() == "Start Simulation") {
              k = Integer.parseInt(JOptionPane.showInputDialog("Enter number of process"));
              jTxF0 = new JTextField[k];
              //JPanel panel = new JPanel();
              for (int i = 0; i < jTxF0.length; i++) {
                jTxF0[i] = new JTextField(10);
                panel.add(jTxF0);
    panel.revalidate();
    panel.repaint();
    for (int i = 0; i < prgsItems.length; i++) {
    JMenuItem item = new JMenuItem(prgsItems[i]);
    item.addActionListener(listen);
    //System.out.println(item.getActionCommand());
    progress.add(item);
    progress.insertSeparator(2);
    for (int j = 0; j < typeItems.length; j++) {
    JMenuItem item = new JMenuItem(typeItems[j]);
    item.addActionListener(listen);
    typemenu.add(item);
    typemenu.insertSeparator(1);
    typemenu.insertSeparator(5);
    JMenuItem item;
    add(progress);
    add(typemenu);
    class GUI
    public void buildGUI()
    JPanel framePanel = new JPanel();
    framePanel.setPreferredSize(new Dimension(400,300));
    JFrame frame = new JFrame("CPU Simulation");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(framePanel);
    frame.setJMenuBar(new FIFO_MenuBar(framePanel));
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    public static void main(String s[])
    SwingUtilities.invokeLater(new Runnable(){
    public void run(){
    new GUI().buildGUI();

  • How can I add KeyListener to JTable editor

    Hi, I want to know how can I add a KeyListener to a JTable editor?
    I want to capture the event when any of the cell in the jtable has a key typed.

    If your goal is to check the entered value, it's more elegant to do this in overriding
    DefaultCellEditor#stopCellEditing and return false when the value is not correct.
    Example from a DateEditor:
            @Override public boolean stopCellEditing() {
                String value = ((JTextField)getComponent()).getText();
                if(!value.equals("")) {
                    try {
                        formatterE.parse(value);
                    } catch (ParseException e) {
                        ((JComponent)getComponent()).setBorder(new LineBorder(Color.red));
                        return false;
                return super.stopCellEditing();
            }

  • JComboBox cann't add KeyListener? Why?

    There is a fragment:
    JComboBox cBox = new JComboBox();
    cBox..setEditable(true);
    cBox.addKeyListener(new KeyAdapter(){
                   @Override
                   public void keyPressed(KeyEvent e) {
                        System.out.println(e.getKeyChar());
    Whatever I press which key,the console print nothing,why?
    And I want to restrict the user's input through this way,any better ideas?
    thanks for ur help!

    For an editable JComboBox, you need to add the KeyListener to the editor component, something like this:
    comboBox.getEditor().getEditorComponent().addKeyListener(...)
    And I want to restrict the user's input through this way,any better ideas?Have a look at the Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Implementing a Document Filter. Next, get the editor component for the JComboBox (which is a JTextField), and add the Document Filter to it.

  • Adding a KeyListener

    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();
    }

  • Disable copy and paste function in jtextfield

    I wish to disable the copy and paste function (CTRL+C and CTRL+V) of the data in the jtextfield... anybody can help?

    I think you can add a KeyListener to listen to those keys and when you get such an input just do nothing. Not tested though.

  • JTextField action listener

    Hi All,
         I have added an action listener to a TextField,im printing the text entered in textfiled by pressing the enter key of keyboard.
          public void actionPerformed(ActionEvent ae) {
                   System.out.println(jtf.getText());
             } my question is as an when i enterd the text in the textfield i want to printit . please help me to solve this.
    Thanks

    Yannix wrote:
    Add a keyListener in your JTextField.
    http://java.sun.com/docs/books/tutorial/uiswing/events/keylistener.html
    I've always thought that it is better to use solutions that use a higher level of abstraction compared to solutions that use a lower level. If so, then using key Binding may be a better solution. If this is wrong, please let me know. You can learn about key Bindings here:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html
    One statement in this tutorial compares key bindings to keylisteners:
    An alternative to key bindings is using key listeners. Key listeners have their place as a
    low-level interface to keyboard input, but for responding to individual keys key bindings are more
    appropriate and tend to result in more easily maintained code. Key listeners are also difficult if
    the key binding is to be active when the component doesn't have focus. Some of the advantages
    of key bindings are they're somewhat self documenting, take the containment hierarchy into
    account, encourage reusable chunks of code (Action objects), and allow actions to be easily
    removed, customized, or shared. Also, they make it easy to change the key to which an action
    is bound. Another advantage of Actions is that they have an enabled state which provides an
    easy way to disable the action without having to track which component it is attached to.
    In the future Swing related question should be posted in the Swing forum.
    http://forum.java.sun.com/forum.jspa?forumID=57
    Agree 100%

  • JTextField - how to se maximum input?

    hi guys, please let me know if u have any sugguestion for this
    ==========================================================
    JButton submitButton = new JButton("Display");
    submitButton.addActionListener(new submitRecord());
    JPanel submitPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    submitPanel.add(new JLabel(" Name: "));
    submitPanel.add(new JTextField());
    ============================================================
    i wanted to set the Field to the limited input
    the
    new JTextField().setColumns(8);
    doesn't seem to work ...

    Yogee's suggestion is probably the better one in the grand scheme of things, but you could also add a keyListener and consume the key event if JTextField.getText().length() is greater than 8.

  • KeyListener and MouseListener...How?

    I have a JTable and I want to add some KeyListener and MouseListener events to do following functions:
    - When PageDown is pressed, function NextPage(){...} is invoked
    - When a row is selected, then press Enter, function Select(){...} is invoked
    - Or when a row is clicked, function Select(){...} is invoked
    - When ESC is pressed function Exit(){...} is invoked
    Thanks all your help and sorry for my poor English :)

    I think you should look at using Actions. Here is a simple example that shows how to map Actions to KeyStrokes:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class KeyboardAction extends JFrame
        public KeyboardAction()
            JPanel panel = new JPanel();
            setContentPane( panel );
            JTextField textField1 = new JTextField("Ctrl+1 or Ctrl+2", 10);
            panel.add( textField1 );
            JTextField textField2 = new JTextField("Ctrl+2", 10);
            panel.add( textField2 );
            //  Change the input map of the text field,
            //  therefore, Ctrl+1 only works for the first text field
            Action action1 = new SimpleAction("1");
            Object key1 = action1.getValue(Action.NAME);
            KeyStroke ks1 = KeyStroke.getKeyStroke(KeyEvent.VK_1, KeyEvent.CTRL_MASK);
            textField1.getInputMap().put(ks1, key1);
            textField1.getActionMap().put(key1, action1);
            //  Change the input map of the panel
            //  therefore, Ctrl+2 works for both text fields added to the panel
            Action action2 = new SimpleAction("2");
            Object key2 = action2.getValue(Action.NAME);
            KeyStroke ks2 = KeyStroke.getKeyStroke(KeyEvent.VK_2, KeyEvent.CTRL_MASK);
            panel.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks2, key2);
            panel.getActionMap().put(key2, action2);
        class SimpleAction extends AbstractAction
            public SimpleAction(String name)
                putValue( Action.NAME, "Action " + name );
            public void actionPerformed(ActionEvent e)
                System.out.println( getValue( Action.NAME ) );
        public static void main(String[] args)
            KeyboardAction frame = new KeyboardAction();
            frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
            frame.pack();
            frame.setVisible(true);
    }Here is section in the Swing tutorial that explains more about key bindings and Actions:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

  • KeyListener function on non edittable

    I have a JTextField that is set to not be edittable. I have a keylistener on it but it doesnt seem to work at all. Is this because the JTextField is set to non edittable? I even tried clicking in the field first before typing the allowed keys but still nothing. Any help would be greatly appreciated...
    and yes, I know that most of my code is not in use/doesnt have anything looking to it, my program is far from being done, im getting one thing done at a time
    package DiceGame;
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextField;
    public class DiceGameMain extends JFrame implements ActionListener
         JPanel status;
         JTextField POINTS, RISK, Risk, WinLose;
         int points = 1000, risk=0;
         JButton roll;
         Dimension res = Toolkit.getDefaultToolkit().getScreenSize();
         String win = "         WIN", lose = "       LOSE";
         boolean enterRisk = true;
    public static void main(String[] args)
              DiceGameMain frame = new DiceGameMain();
              frame.setVisible(true);
    public DiceGameMain()
              setName("Dice Game - Alpha");
              setSize(400, 300);
              setLocation((int)(res.getWidth()/2)-(getWidth()/2), (int)(res.getHeight()/2)-(getHeight()/2));
              setResizable(false);
              setLayout(null);
    //     Bottom status bar
              status = new JPanel();
              status.setVisible(true);
              status.setSize(390, 40);
              status.setLocation(getWidth()/2-status.getWidth()/2-3, getHeight()-73);
              status.setLayout(null);
              status.setBackground(Color.BLACK);
              add(status);
              POINTS = new JTextField ("Points: "+points);
              POINTS.setSize(100,30);
              POINTS.setLocation(5, 5);
              POINTS.setEditable(false);
              POINTS.setBackground(Color.GREEN);
              status.add(POINTS);
              Risk = new JTextField(risk+"");
              Risk.setSize(55, 30);
              Risk.setLocation(status.getWidth()-60, 5);
              Risk.setEditable(false);
              Risk.setBackground(Color.GREEN);
              status.add(Risk);
              RISK = new JTextField ("Risk:");
              RISK.setSize(35,30);
              RISK.setLocation(status.getWidth()-RISK.getWidth()-60, 5);
              RISK.setEditable(false);
              RISK.setBackground(Color.GREEN);
              status.add(RISK);
              WinLose = new JTextField();
              WinLose.setSize(80,30);
              WinLose.setLocation(status.getWidth()/2-WinLose.getWidth()/2, 5);
              WinLose.setEditable(false);
              WinLose.setBackground(Color.BLACK);
              status.add(WinLose);
              setDefaultCloseOperation(EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent event)
         if(enterRisk==true) // 95 - 105 | 48 - 57
              Risk.addKeyListener(new KeyListener()
                   public void keyReleased(KeyEvent arg0)
                   public void keyTyped(KeyEvent arg0)
                   public void keyPressed(KeyEvent arg0)
                        if((arg0.getID() <= 105 && arg0.getID() >= 95) || (arg0.getID() <= 57 && arg0.getID() >= 48))
                             if(Integer.parseInt(Risk.getText()+arg0) < points)
                                       Risk.setText(Risk.getText()+arg0);
                             if(Integer.parseInt(Risk.getText()+arg0) > points)
                                       Risk.setText(points+"");
    public void ifStatements()
         if(risk==points)
                   RISK.setBackground(Color.ORANGE);
         if(risk!=points)
                   RISK.setBackground(Color.GREEN);
         if(points <= 500 && points > 250)
                   POINTS.setBackground(Color.YELLOW);
         if(points <= 250)
                   POINTS.setBackground(Color.RED);
         if(points > 500)
                   POINTS.setBackground(Color.GREEN);
    }

    There are so many of wrong parts in your code.
    You must learn basics for Java language and Java GUI
    programming."my program is far from being done, im getting one thing done at a time"
    Just one thing (among hundreds):
    Where's your addActionListener() call ?yes i did forget to add my addActionListener, that has been added at the bottom of the public method. Problem persists still.

Maybe you are looking for

  • Windows 7 Boot Camp resolution capped at 1280x1024

    I have installed Windows 7 on my late 2009 21.5" iMac, using the bootcamp Assistant (v5.1.2) packed with Mavericks (OSX 10.9.5). The installation went smoothly, however my Windows screen resolution cannot go any higher than 1280x1024, and I would obv

  • My Win 7 PC isn't visible after lion boot up

    Hi all After updating to lion and all the dissapointments so far, one of the worst things for me is that my Win 7 and Win XP PC's are not visible in the finder for the first 8-15 minutes after the boot. Even when i try to connect them directly (cmd +

  • Web Sharing Issues... No PHP support

    Good morning all, I guess it's fair to say that we are having problems with PHP, but I'm curious to see if anyone is having the same issues that I am... here is the story: I have two Mac's, a powerbook G4, and a powermac G5. I decide to wipe the hard

  • Get the last query from the current user

    Is there a way to get the last query of the current user, so every query could be log with a database trigger? Let's just say I execute: DELETE xxxx; I tried : SELECT T.SQL_TEXT FROM V$SQLAREA T where ADDRESS=(SELECT prev_sql_addr FROM v$session wher

  • Aperture error opening database for library

    I was working in Aperture--deleting photos--when it crashed. My Mac Book Pro rebooted but in trying to open Aperture after it rebooted, I got this message: "There was an error opening the database for the library "/Users/rick/Pictures/Aperture Librar