Reputation: 193
So everything in my program works, except for the mouse and the keyboard listeners. I've got a couple actionListeners working on Jbuttons that do exactly what I'm trying to do here, but the assignment says it has to work with all three. So I would like to know why it compiles, but doesn't work. Am I doing something wrong?
panel.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
shape.addSides();
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
shape.subSides();
}
}
@Override
public void keyReleased(KeyEvent e) {
}
}
);
panel.addMouseListener(new MouseListener(){
@Override
public void mouseEntered(MouseEvent e){
if(e.getButton() == MouseEvent.BUTTON1){
shape.addSides();
}
if(e.getButton() == MouseEvent.BUTTON3){
shape.subSides();
}
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
);
Upvotes: 1
Views: 1750
Reputation: 285403
Regarding KeyListener: it won't work unless the listened-to component is focusable and has focus. So you will want to call setFocusable(true)
and requestFocusInWindow()
on your JPanel. As for the MouseListener -- something else may be taking the mouse event and preventing it from reaching your JPanel. To debug this you need to post a minimal, compilable, runnable example program.
Also regarding your MouseListener, you're checking getButton()
in a mouseEntered event which makes no sense. The buttons are not involved in this type of event. Are you instead meaning to check mouseDragged(...)
of a MouseMotionListener?
Upvotes: 3