I have a GUI made using javax.swing and java.awt, the request focus was working on keeping the text field in focus, so that a user can just start with a keyboard. I then added buttons for each integer 0-9, aswell as a clear field button. However the focus now always starts on a button.
The focus still returns to the textField whenever I click a button or if I initiate the focus it remains in the textField, how can I fix this problem and have the focus on the text field everytime the window opens?
Example Number Buttons
JButton btn0 = new JButton("0");
panel.add(btn0);
btn0.setBounds(50, 360, 50, 50);
btn0.setHorizontalAlignment(SwingConstants.CENTER);
btn0.setForeground(Color.BLACK);
btn0.setFont(new Font("Arial", Font.BOLD, 20));
btn0.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userIn = txtGuess.getText() + btn0.getText();
txtGuess.setText(userIn);
}
});
textField Code
txtGuess = new JTextField();
txtGuess.setBounds(325, 220, 100, 35);
panel.add(txtGuess);
txtGuess.setFont(new Font("Arial", Font.BOLD, 25));
txtGuess.setHorizontalAlignment(SwingConstants.CENTER);
txtGuess.setBackground(Color.decode("#206BA4"));
txtGuess.setForeground(Color.decode("#EBF4FA"));
txtGuess.setBorder(loweredBorder);
txtGuess.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
checkGuess();
}
});
The end of checkGuess();
finally {
txtGuess.requestFocus(); //sets focus to the text box after checking guess
txtGuess.selectAll(); //highlights all text in the text field so UX is improved
if (attempt >= 10) {
lblOutput.setText("You lose! Try Again?");
newGame();
}