2

When I press a key for some time, the background color of the key doesn't restore to original color in keyReleased function.What am I doing wrong. If you could redirect me to some site contain tutorial on how to make programs like this with examples, it will be very helpful. Here is the code:

public void keyPressed(KeyEvent event)
    {
        int code= event.getKeyCode();
        String x,h;

        for(int i=0;i<names.length;i++)
        {
            s=names[i];
            x=s.trim();

            if(x.contentEquals(event.getKeyText(code)) )
            {
                backColor=but[i].getBackground();
                but[i].setBackground(Color.RED);
                break;
            }
        }
        switch(event.getKeyCode())
        {
        case KeyEvent.VK_BACK_SLASH:
            h=" \\ ";
            for(int i=0;i<but.length;i++)
            {
                if(h.contentEquals(but[i].getText()))
                {
                    backColor=but[i].getBackground();
                    but[i].setBackground(Color.RED);
                    buttonIndex=i;
                    break;
                }
            }
            break;
    }
public void keyReleased(KeyEvent event)
    {
        String x;
        int code= event.getKeyCode();

        for(int i=0;i<names.length;i++)
        {
            s=names[i];
            x=s.trim();

            if(x.contentEquals(event.getKeyText(code)) && !s.contentEquals("                             "))
            {System.out.println("outside");
                but[i].setBackground(backColor);
                break;
            }
            else
                if(s.contentEquals("                             "))
                {
                    but[buttonIndex].setBackground(backColor);
                }
        }
    }
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Alfred
  • 1,543
  • 7
  • 33
  • 45

1 Answers1

2
  • don't use Keylistener for Swing JComponents, use KeyBindings instead

  • your JFrame, JPanel, JComponent must be focusable (setFocusable)

  • in one moment only one of JComponent can be focusable, then your program will be focus_hunter this not caused by using KeyBindings

  • for better help sooner post an SSCCE, short, runnable, compilable

Community
  • 1
  • 1
mKorbel
  • 109,525
  • 20
  • 134
  • 319