Search code examples
javaswinguser-interfacejbuttonjtextfield

How to remove focus from textfield and set it on button?


It is the simple counter gui program in these program by pressing right arrow counter is incremented by 1 but the problem is whenever i run the program then pressing the right arrow the counter is not increment by 1 but by pressing the right arrow the cursor in textfield shifts from left to right why this happens ?

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

public class CounterDemo implements KeyListener
{
    JTextField jtf;
    JButton jb,jb1;
    int i=0;
    public CounterDemo ()
    {
        JFrame jf = new JFrame();
        jf.setBounds(100,100,400,400);
        jf.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        jf.setLayout(null);


        jtf = new JTextField("0");
        jtf.setBounds(60,10,50,20);
        jf.add(jtf);

        JButton jb = new JButton("next");
        JButton jb1 = new JButton("prev");
        jb.setBounds(10,35,75,20);
        jb1.setBounds(90,35,75,20);

        jf.add(jb);
        jf.add(jb1);

        jb.addKeyListener(this);
        jb1.addKeyListener(this);
        jf.setVisible(true);
    }
    public static void main(String[] args)
    {
        new CounterDemo();
    }

    public void keyPressed(KeyEvent ke)
    {
        if(ke.getKeyCode() == KeyEvent.VK_RIGHT)
        {
            i++;
            jtf.setText(" "+i);
        }
        else if (ke.getKeyCode() == KeyEvent.VK_LEFT)
        {
            i--;
            jtf.setText(" "+i);
        }
    }

    public void keyTyped(KeyEvent ke)
    {

    }

    public void keyReleased(KeyEvent ke)
    {

    }
}

Solution

  • Add jtf.setFocusable(false) so that the text field is not in focus initially.

    Edit: As Abra said, this would make the text field never be in focus. An alternative solution is to do something like jb.grabFocus(), for the button to get focus instead of the text field.