java初学者if / else如果有问题
发布时间:2020-12-15 05:06:32 所属栏目:Java 来源:网络整理
导读:试图设置String变量的代码块似乎出现了问题,因为无论我在运行程序时做什么,对话框总是显示otto.有谁知道我在这里做错了什么? 谢谢, 猎食 import java.awt.FlowLayout;import java.awt.event.ActionListener;import java.awt.event.ActionEvent;import javax
试图设置String变量的代码块似乎出现了问题,因为无论我在运行程序时做什么,对话框总是显示otto.有谁知道我在这里做错了什么?
谢谢, import java.awt.FlowLayout; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.JOptionPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPasswordField; import javax.swing.JTextField; public class SmallTingz extends JFrame { private JLabel item1; private JTextField tf; private JTextField tf2; private JTextField tf3; private JPasswordField pf; public SmallTingz() { super("The Title"); setLayout(new FlowLayout()); JTextField tf = new JTextField("Cool Beans"); JTextField tf2 = new JTextField("UnCool Beans"); JTextField tf3 = new JTextField("Hot Beans"); JPasswordField pf = new JPasswordField("password"); add(tf); add(tf2); add(tf3); add(pf); thehandler handler = new thehandler(); tf.addActionListener(handler); tf2.addActionListener(handler); tf3.addActionListener(handler); pf.addActionListener(handler); } private class thehandler implements ActionListener { public void actionPerformed(ActionEvent event) { String string; if (event.getSource() == tf) string=String.format("field1: %s",event.getActionCommand()); else if (event.getSource() == tf2) string=String.format("field2: %s",event.getActionCommand()); else if (event.getSource() == tf3) string=String.format("field3: %s",event.getActionCommand()); else if (event.getSource() == pf) string=String.format("passfield: %s",event.getActionCommand()); else string="otto"; JOptionPane.showMessageDialog(null,string); } } } 解决方法
在SmallTingz()构造函数中,删除所有变量声明.您的声明是
hiding成员变量.
更改 JTextField tf = new JTextField("Cool Beans"); JTextField tf2 = new JTextField("UnCool Beans"); JTextField tf3 = new JTextField("Hot Beans"); JPasswordField pf = new JPasswordField("password"); 至 tf = new JTextField("Cool Beans"); tf2 = new JTextField("UnCool Beans"); tf3 = new JTextField("Hot Beans"); pf = new JPasswordField("password"); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |