java swing 设置文本框(输入框)限制只能输入数字(完美解决)

java swing 设置文本框只能输入数字(完美解决)

核心代码

private JTextField textField_1 = new JTextField();
		textField_1.setBounds(10, 10, 66, 21);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		textField_1.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				
				String key="0123456789";
				if(key.indexOf(e.getKeyChar())<0){
					e.consume();//如果不是数字则取消
				}
			}
		});

整体代码 text.java


import java.awt.EventQueue;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JTextField;
import java.awt.BorderLayout;

public class Text {

	private JFrame frame;
	private JTextField textField;
	private JTextField textField_1;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Text window = new Text();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Text() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 450, 300);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		textField_1 = new JTextField();
		textField_1.setBounds(10, 10, 66, 21);
		frame.getContentPane().add(textField_1);
		textField_1.setColumns(10);
		textField_1.addKeyListener(new KeyAdapter() {
			public void keyTyped(KeyEvent e) {
				
				String key="0123456789";
				if(key.indexOf(e.getKeyChar())<0){
					e.consume();//如果不是数字则取消
				}
			}
		});
		
		
	
	}
}

       });

PS: 如果想要在字符里面输入其他的字符,只需要在String key = “” 字符串添加即可想要输入的字符串即可;
例子:String key = “A” 那么文本框就只能输入A

你可能感兴趣的:(java,java,开发语言)