This is my Full code. It will help you understand.
I try to make what changes state when i clicking Button or pressing keyboard. when I pressing ENTER it changes START to STOP(or STOP to START). And when I clicked button START state changes to start. And when I clicked button STOP, state changes to STOP. I add System.out.println() for checking my code working correctly.
First time It works correctly . I can change state by pressing keyboard(ENTER)(I can see "Now Start" or "Now Stop")
But KeyListener(ENTER) doesn't work after click Button.
I don't know why... pleas help me.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ServerClass3 extends JFrame
{
String SS = "Now Stop";
public ServerClass3()
{
JButton btn_start = new JButton("Start");
JButton btn_stop = new JButton("Stop");
JButton btn_quit = new JButton("quit");
btn_start.setLocation(20, 20);
btn_start.setSize(100, 40);
btn_stop.setLocation(140, 20);
btn_stop.setSize(100, 40);
btn_quit.setLocation(260, 20);
btn_quit.setSize(100, 40);
btn_start.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "Now Start";
System.out.println("ss is " + SS);
}
});
btn_stop.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "Now Stop";
System.out.println("ss is " + SS);
}
});
btn_quit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
SS = "quit";
System.out.println("ss is " + SS);
}
});
KeyPanel p = new KeyPanel();
setContentPane(p);
p.add(btn_start);
p.add(btn_stop);
p.add(btn_quit);
setSize(300, 300);
setVisible(true);
p.requestFocus();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
class KeyPanel extends JPanel
{
public KeyPanel()
{
this.addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if (SS.equals("Now Stop"))
{
SS = "Now Start";
System.out.println(SS);
}
else
{
SS = "Now Stop";
System.out.println(SS);
}
}
}
});
}
}
public static void main(String[] args)
{
new ServerClass3();
}
}
This happens because after pressing one of the buttons, the focus is on the buttons. Because of this, the buttons soak up all events and none go through to your KeyPanel. You know this is true, because when starting the program and pressing spacebar, nothing happens. But as soon as you press a button, when pressing spacebar it executes the actionPerformed event of this button.
To fix this, set all buttons to not be focusable with the setFocusable function:
button.setFocusable(false);
This way, no matter what or where you click on the window, the buttons never get focused and all events get registered by the KeyPanel.