gpt4 book ai didi

Java Swing JTextField - 只有数字

转载 作者:行者123 更新时间:2023-11-29 09:35:33 24 4
gpt4 key购买 nike

<分区>

我正在制作一个转换温度的小型 Java Swing Applet:TempConvert.java

这是我的代码:

package swing;

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

/** Celcius to Fahrenheit Converter
* @version 1.0
* @author Oliver Ni
*/

public class TempConvert extends JApplet{
JLabel result;
JRadioButton ctof;
JRadioButton ftoc;
JTextField deg;
JLabel degLab;
JButton convert;

public void convert() {
if (ctof.isSelected() == true) {
result.setText("<html><br>" + Integer.toString(Integer.parseInt(deg.getText()) * 9 / 5 + 32) + "<sup>o</sup> F</html>");
} else if (ftoc.isSelected() == true) {
result.setText("<html><br>" + Integer.toString((Integer.parseInt(deg.getText()) - 32) * 5 / 9) + "<sup>o</sup> C</html>");
} else {
result.setText("<html><br>Error.</html>");
}
}

public void makeApplet() {
setLayout(new FlowLayout());
ctof = new JRadioButton("Celcius to Fahrenheit");
ftoc = new JRadioButton("Fahrenheit to Celcius");
convert = new JButton("Convert");
result = new JLabel("");
ButtonGroup group = new ButtonGroup();
group.add(ctof);
group.add(ftoc);

deg = new JTextField(10);
degLab = new JLabel("<html><sup>o</sup></html>");
convert.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
convert();
}
});
add(ctof);
add(ftoc);
add(deg);
add(degLab);
add(convert);
add(result);
}

public void init() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeApplet();
}
});
} catch(Exception e) {
System.out.println("Error loading because " + e);
}
}
}

我想将 JTextField deg 限制为仅整数。有什么办法可以做到吗?

如有任何帮助,我们将不胜感激!

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com