Home > other >  Java - KeyListener performs code in different class
Java - KeyListener performs code in different class

Time:04-28

I'm currently coding a sort of quiz in Java and I'm having problem with KeyListeners. I currently have 2 classes with KeyListeners but they're sort of interfering with each other. One class is when you play the quiz and if you press esc a JOptionPane shows up asking the user if they really want to leave, the problem is that this also pops up when you press esc in another class where it shouldn't be happening. Does anyone has any idea why?

CodePudding user response:

This sounds like you should check if the listeners are registered properly.

I'am guessing you build something like this:

public class ListenerA implements KeyListener
{ ... }

public class ListenerB implements KeyListener
{ ... }

public class QuizPanel extends JPanel
{
    private Component componentA = ...;
    private Component componentB = ...;

    public QuizPanel()
    {
        // Be very careful here to not mix up A and B
        componentA.addKeyListener(new ListenerA());
        componentB.addKeyListener(new ListenerB());
    }
}

If that does not help, can you please provide your code or a sample that yields the same problem?

CodePudding user response:

Yeah sure, here's where I add the KeyListener in the class where it bugs the most

   public class Play implements MouseListener, KeyListener
   {
    File_Methods fm = new File_Methods();
    GUI_Methods gm = new GUI_Methods();
    
    JFrame frame;
    int noq, corr_ans, choice = 0, curr_qna = 0, points = 0;
    int[] qna_ids;
    JLabel quest, A1, A2, A3, A4, exit, multi_butt;
    boolean clickable = true;
    
    public void genPlayFrame(JFrame parent_frame)
    {
        frame = parent_frame;
        frame.addKeyListener(this);
        more gui code...

Then this is where I code the keylistener

    @Override
    public void keyPressed(KeyEvent  arg0){}
    @Override
    public void keyReleased(KeyEvent arg0){}
    @Override
    public void keyTyped(KeyEvent ke_p)
    {
        if(ke_p.getKeyChar() == KeyEvent.VK_ESCAPE)
        {
            int alt = gm.exit_y_n("progress");
            if(alt == 0)
                back();
        }
        else if(ke_p.getKeyChar() == '\n' && multi_butt.getText().equals("Answer"))
            answer();
        else if(ke_p.getKeyChar() == '\n' && multi_butt.getText().equals("Next"))
            next();
    } 

gm.exit_y_n() is the JOptionPane that asks if the user wants to leave, this popup also shows up when you press esc in another class

  • Related