Reputation: 29
I'm trying to write a program where the user can type in numbers but not letters or symbols. I have a textfield that is not editable because I want only acceptable user input keys to be displayed on the textfield. This is the basic structure of my code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class SampleProgram extends JFrame implements ActionListener, KeyListener
{
private Container container;
private JPanel panel;
private JTextField textField;
private JButton button;
private String[] names = {"1", "2", "3", "4", "5", "6", "7", "8", "9"};
public SampleProgram()
{
container = getContentPane();
panel = new JPanel();
textField = new JTextField();
textField.setEditable(false);
contain.add(textField);
addKeyListener(this);
button = new JButton("Some Action Button");
button.addActionListener(this);
panel.add(button);
container.add(panel);
setResizable(false);
setVisible(true);
}
public void keyPressed(KeyEvent event) {}
public void keyReleased(KeyEvent event) {}
public void keyTyped(KeyEvent event)
{
String action = String.valueOf(event.getKeyChar());
for (String s : names)
if (action.equalsIgnoreCase(s))
{
someAction(action);
return;
}
}
public void actionPerformed(ActionEvent event)
{
String action = ((JButton)event.getSource()).getText();
someAction(action);
}
private void someAction(String input)
{
textField.setText(input);
}
}
This is the stripped down version of my code. My ActionListener is doing what it is supposed to do, but my KeyListener isn't working at all. I tried to add KeyListener to textField as well, but that didn't work either. How do I get my program to read in the user key input? To figure out the error, I tried putting in the code textField.setText(action) in the keyTyped method, and I learned that my code wasn't even entering the keyTyped method.
Upvotes: 1
Views: 810
Reputation: 324147
Use a JFormattedTextField
. You can set a MaskFormatter
to allow only numeric digits.
Read the section from the Swing tutorial on How to Use Formatted Text Fields for more information and examples.
Upvotes: 2