某些東西似乎與試圖設置字符串變量的代碼塊有關,不管我在運行程序時做什麼,對話框總是顯示otto。有誰知道我在這裏做錯了嗎?java初學者if/else如果問題
感謝, 獵食
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);
}
}
}
您應該在if語句中使用「.equals()」而不是「==」。例如if(event.getSource()。equals(tf))「tf」和「event.getSource()」必須是相同類型 – fsonmezay
嘗試通過調試器運行此操作,打破actionPerformed。然後檢查事件的運行時間值。 – jpm
@fsonmezay getSource()返回發出源的實際組件的引用。因此,在這種情況下,對參考平等進行測試實際上是正確的。否則,如果您有兩個subl壓縮的JButton,其overrode等於基於它們的標籤,則無法區分兩個不同按鈕之間按下等同標籤的區別。 – jpm