Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Are you sure that</p> <pre><code>private void a33FocusGained(java.awt.event.FocusEvent evt) { selectedTextField = (JTextComponent) evt.getSource(); } </code></pre> <p>is ever called? I guess your class should implement FocusListener and add something like</p> <pre><code>passwordField.addFocusListener(this); @Override public void focusGained(FocusEvent e) { selectedTextField = (JTextComponent) e.getSource(); } @Override public void focusLost(FocusEvent e) { selectedTextField = null; } </code></pre> <p>This is a sample code of what you should do (if I understood you correctly), note that at first you need to set cursor to the password field and after that the button will work, however you can see the bad side of this approach in the focusLost method </p> <pre><code>public class Snippet implements ActionListener, FocusListener { public JFrame totalGUI = new JFrame(); private JPanel buttonPanel; private JButton B9; public Snippet() { createContentPane(); } public void createContentPane() { buttonPanel = new JPanel(new GridBagLayout()); B9 = new JButton("9"); B9.addActionListener(this); buttonPanel.add(B9); JPasswordField passwordField = new JPasswordField(20); passwordField.setSize(120, 30); passwordField.addFocusListener(this); buttonPanel.add(passwordField); totalGUI.getContentPane().add(buttonPanel); totalGUI.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); totalGUI.pack(); } private JTextComponent selectedTextField; @Override public void actionPerformed(ActionEvent evt) { if (evt.getSource() == B9 &amp;&amp; selectedTextField != null) selectedTextField.setText(selectedTextField.getText() + "9"); } public static void main(String[] args) { new Snippet().totalGUI.setVisible(true); } @Override public void focusGained(FocusEvent e) { if(e.getSource() instanceof JTextComponent) selectedTextField = (JTextComponent) e.getSource(); } @Override public void focusLost(FocusEvent e) { // when you push the button the text field will lose focus // selectedTextField = null; } </code></pre> <p>}</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload