1

I was demonstrating my program by basically mashing keys on the number pad to get some dummy data in there really quickly, and discovered that occasionally that causes invalid input to be entered. It seems like some sort of threading issue, but my understanding of Swing events is that they basically are fired sequentially from the same thread. I am not explicitly creating any threads of my own, but I am doing a lot of custom painting using paintComponent(Graphics g). Most keypresses eventually trigger a repaint() deep in the stack. Could that be causing my issue? Why? If so, any idea how to fix it? If not, any idea what else it could be?

Also, does anyone know how to make an automated test for this? The relevant event handlers are shown below.

public void keyTyped(KeyEvent e)
{
    if (e.getKeyChar() == myKeyChar)
        runPrimaryFunction(); // Does some calculations and triggers a repaint
}

public void keyPressed(KeyEvent e)
{
    if (e.getKeyCode() == myKeyCode)
        runPrimaryFunction();
}

/********* Another class listening to the same JFrame ********/

public void keyPressed(KeyEvent e)
{
    if (e.getKeyCode() == KeyEvent.VK_UP)
    {
        scrollUp();
        repaint();
    }
    else if (e.getKeyCode() == KeyEvent.VK_DOWN)
    {
        scrollDown();
        repaint();
    }
}
Karl Bielefeldt
  • 47,314
  • 10
  • 60
  • 94
  • You aren't giving me enough information. I don't know what the error is, and I don't have complete source (even if I were inclined to read it). I don't know what you mean by "invalid input". You have evidently decided that these couple-dozen lines of "relevant" code contain something that I can point to and say "There's your problem!". If you really want help, you should put more effort into giving potential helpers what they'll need. You might mention the overall technology (Swing) in the title as well. – arcy Feb 22 '13 at 16:10

2 Answers2

3

You should almost certainly be using Key Bindings. The arrow keys are typically bound to scroll pane actions by default, and you can evoke those actions yourself as shown here. Also consider implementing the Scrollable interface.

If you use Key Listener, note this essential difference: a keyTyped() "event occurs when a key press is followed by a key release." KeyEventDemo illustrates how the events are interleaved.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

Turns out the problem was an inconspicuous timer task that called repaint() and was not thread safe. Also, I should have used javax.swing.Timer instead of java.util.Timer, since the thread safety issue was dealing with swing components. I am still interested in answers about the automated testing part of my question.

Karl Bielefeldt
  • 47,314
  • 10
  • 60
  • 94
  • To move it up in the active queue, edit your question to indicate your changes and highlight the remaining issue. For example, do you mean checking the timestamps? – trashgod Feb 22 '13 at 19:04