[英]Specify range for textfield in java applet
这是我发布的代码:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="front" width=500 height=500></applet> */
public class front extends Applet implements ActionListener {
String msg="";
TextArea text,text1;
TextField txt;
Button load, enter;
public void init() {
enter=new Button("Enter");
load=new Button("Load");
txt=new TextField(5);
text=new TextArea(10,15);
add(load);
add(text);
add(txt);
add(enter);
load.addActionListener(this);
txt.addActionListener(this);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Load")) {
msg = "You pressed Load";
} else {
if(txt.getText().toString().equals ("6")) {
msg="Set the text for 6";
text.setText("Text");
} else {
msg="Invalid number";
text.setText("");
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg,350,250);
}
}
如您所见,当文本字段中的值等于6时,它会显示一个味精。但现在我希望仅在5-6范围内显示该味精。 所以我尝试了以下代码
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="front" width=500 height=500></applet> */
public class front extends Applet implements ActionListener {
String msg="";
TextArea text,text1;
TextField txt;
Button load, enter;
public void init() {
enter=new Button("Enter");
load=new Button("Load");
txt=new TextField(5);
text=new TextArea(10,15);
add(load);
add(text);
add(txt);
add(enter);
load.addActionListener(this);
txt.addActionListener(this);
enter.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("Load")) {
msg = "You pressed Load";
} else {
String a = txt.getText();
int a1=Integer.parseInt(a); //I also used Integer.valueOf(a)
if(a1>="5"&&a1<="6")
{
msg="Set the text";
text.setText("Text");
} else {
msg="Invalid number";
text.setText("");
}
}
repaint();
}
public void paint(Graphics g) {
g.drawString(msg,350,250);
}
}
但是当我编译这段代码时,出现以下错误:
运算符> =不能应用于int,java.lang.String运算符<=不能应用于int,java.lang.String
我知道getText()返回一个字符串,所以我使用parseInt将其转换为Integer,但我无法理解该错误。
您正在尝试将int与字符串值进行比较。
if(a1>="5"&&a1<="6") // 5 and 6 are string representation whereas a1 is int
需要
if(a1>=5 && a1<=6) // 5 and 6 are int representation
注意:如果要比较字符串,请使用.equals()。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.