我导入了所有必要的类并且没有错误。但是当我在任何文本字段上按 enter 时,提示窗口是空白的,而不是它打算显示的字符串。 如果问题出在 JOptionPane 或者什么,我不知道。当我第一次运行我的代码时,它在第二次运行时运行良好,但出现空白提示。
public class fish extends JFrame{
private JTextField item1;
private JTextField item2;
private JTextField item3;
private JPasswordField password;
public fish(){
super("Title");
setLayout(new FlowLayout());
item1=new JTextField(10);
add (item1);
item2=new JTextField("Enter Txt here");
add (item2);
item3=new JTextField("Uneditable",20);
item3.setEditable(false);
add (item3);
password = new JPasswordField("MyPass");
add(password);
thehandler handler = new thehandler();
item1.addActionListener(handler);
item3.addActionListener(handler);
item2.addActionListener(handler);
password.addActionListener(handler);
}
private class thehandler implements ActionListener{
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==item1)
String.format("field1: %s", event.getActionCommand());
else if(event.getSource()==item2)
String.format("field2: %s", event.getActionCommand());
else if(event.getSource()==item3)
String.format("field3: %s", event.getActionCommand());
else if(event.getSource()==password)
String.format("Password Field: %s", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
}
}
public class apples{
public static void main(String args[]){
fish tuna = new fish();
tuna.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
tuna.setSize(350,100);
tuna.setVisible(true);
}
}
最佳答案
您正在显示一个空字符串。这里:
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==item1)
String.format("field1: %s", event.getActionCommand());
else if(event.getSource()==item2)
String.format("field2: %s", event.getActionCommand());
else if(event.getSource()==item3)
String.format("field3: %s", event.getActionCommand());
else if(event.getSource()==password)
String.format("Password Field: %s", event.getActionCommand());
JOptionPane.showMessageDialog(null, string);
}
您在哪里为字符串变量 string
赋值?此外,您永远不会从 JTextField 中获取文本,而是获取从未分配的 actionCommand 字符串。
即,
public void actionPerformed(ActionEvent event){
String string = "";
if(event.getSource()==item1) {
string = String.format("field1: %s", item1.getText())
}
else if(event.getSource()==item2) {
string = String.format("field2: %s", item2.getText());
}
else if(event.getSource()==item3) {
string = String.format("field3: %s", item3.getText());
}
else if(event.getSource()==password) {
string = String.format("Password Field: %s", new String(password.getPassword()));
}
JOptionPane.showMessageDialog(null, string);
}
- 顺便说一句,在实际程序中,您永远不会想要执行
new String(password.getPassword())
,因为这会使您的程序非常不安全,因为密码很容易被窃取. - 旁白 #2:在您的编程教育的这个阶段,您会希望将每个 block 用 { } 大括号括起来。安全总比后悔好。
- 旁白 #3:您需要学习和使用 Java 编码约定,包括以大写字母开头的类名。这样其他人一眼就能更好地理解您的代码。
关于java - java中的事件处理程序...程序没有错误,但在事件操作未显示后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24699044/