我正在制作GUI。用户以整数形式输入年份,并在GUI上显示该年份。但问题是我只想从用户输入4个整数。如果用户输入5个整数值,则显示JOptionPane
消息,请再次输入。但我不知道该怎么做。
代码:Java Swing TextField整数值问题
public class A extends JFrame{
private JTextField tx;
private JLabel year;
private JButton bt;
private JLabel at;
public A(){
super("Frame");
getContentPane().setLayout(null);
tx= new JTextField();
tx.setBounds(150, 165, 128, 27);
getContentPane().add(tx);
year= new JLabel("Enter Year :");
year.setBounds(178, 133, 69, 27);
getContentPane().add(year);
at= new JLabel();
at.setFont(new Font("Tahoma", Font.PLAIN, 17));
at.setBounds(165, 295, 189, 27);
getContentPane().add(at);
bt= new JButton("Submit");
bt.setBounds(178, 203, 84, 27);
getContentPane().add(bt);
bt.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
String w = tx.getText();
int p = Integer.parseInt(w);
at.setText(""+p);
}
});
setSize(450,450);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
}
主要
public class Main {
public static void main(String[] args) {
A obj = new A();
}
}
转换使用将String.valueOf(整数对象),然后检查字符串的长度的整数串... –
使用'DocumentFilter'用于此目的的同时解决两个一样的东西。首先要[只允许JTextField中的数字](http://stackoverflow.com/a/9478124/1057230)和[设置最大字符数量](http://stackoverflow.com/a/8883693/1057230),可以插入 –
@nIcE cOw可以请你给我一个代码如何实现这个程序 – hamel123