Java 如何编写一个小程序,让屏幕跟踪用户迄今为止输入的最大数字
我知道如何在文本字段中添加文本/数字,但我不知道如何编写一个小程序,让屏幕跟踪用户迄今为止输入的最高数字Java 如何编写一个小程序,让屏幕跟踪用户迄今为止输入的最大数字,java,Java,我知道如何在文本字段中添加文本/数字,但我不知道如何编写一个小程序,让屏幕跟踪用户迄今为止输入的最高数字 public class Test extends Applet { TextField t1; String tekst, tekst1; int num1, num2,num3; public void init() { t1 = new TextField("", 30); t1.addActionListener(new TextListener());
public class Test extends Applet {
TextField t1;
String tekst, tekst1;
int num1, num2,num3;
public void init() {
t1 = new TextField("", 30);
t1.addActionListener(new TextListener());
add(t1);
tekst = "";
}
public void paint(Graphics g) {
setSize(400, 400);
t1.setBounds(20, 60, 80, 20);
g.drawString("Highest number: " + num1, 20, 50);
}
class TextListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
repaint();
tekst = t1.getText();
num1 = Integer.parseInt(tekst);
}
}
}根据检查哪个数字更高的算法,将num1初始化为0或接受的最低数字,然后:
try{
num2 = Integer.parseInt(t1.getText());
if(num2 > num1)
num1 = num2;
//print num1 to wherever you want the largest value to show
reprint();
}
catch(RuntimeException e)
{
//tell the user to input a valid number;
}
需要注意的几点:
我认为第一条建议是“不要编写小程序”。这是90年代早期的技术,现代浏览器不支持这种技术。我建议您编写一个Swing或JavaFX应用程序,您不需要重写paint方法。只需添加一个JLabel以显示最高值,并在TextListener中设置JLabel的文本。同时删除actionPerformed中对repaint()的调用。@keuleJ注意这是一个
Applet
,而不是JApplet
。这使用AWT,而不是Swing。我想你的建议可以改为使用标签
@realponsignist啊,当然可以。