我試圖構建一個基本的遊戲,其中用戶對州首府的知識進行了測試。在這個階段,我只是想設置一些按鈕的基本功能。JAVA中的ActionPerformed方法中的IF語句
我試圖得到它,以便當用戶鍵入一個正確答案對應的字符串時,程序顯示「正確!」。我試過使用IF ELSE語句,但即使輸入正確的答案,它也會輸出「WRONG!」。這可能很簡單,但我無法發現它。如果有人能夠指引我,我會感激不盡。我非常初學者也許這完全是錯誤的方式去了解它,但這裏是我到目前爲止有:
public class Main {
public static void main(String[] args){
Gui a = new Gui();
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Gui extends JFrame{
private static final long serialVersionUID = 1L;
JPanel row1 = new JPanel();
JLabel instructions = new JLabel("What is the capital of Alabama?");
JPanel row2 = new JPanel();
JLabel aLabel = new JLabel("Answer: ");
JTextField aField = new JTextField(14);
JPanel row3 = new JPanel();
JButton submit = new JButton("Submit");
JButton reset = new JButton("Reset");
public Gui() {
super("State Capitals Game");
setLookAndFeel();
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setResizable(false);
setLayout(new GridBagLayout());
GridBagConstraints gc = new GridBagConstraints();
gc.insets = new Insets(5,5,5,5);
gc.gridx = 0;
gc.gridy = 0;
add(instructions, gc);
gc.gridx = 0;
gc.gridy = 1;
add(aLabel, gc);
gc.gridx = 0;
gc.gridy = 2;
add(aField, gc);
gc.gridwidth = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 4;
add(submit, gc);
///this is where I'm stuck////
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String userIP = aField.getText();
String mg = "Montgomery";
if(userIP == mg){
System.out.println("correct!");
}else{
System.out.println("WRONG!");
}
}
});
gc.gridwidth = 3;
gc.fill = GridBagConstraints.HORIZONTAL;
gc.gridx = 0;
gc.gridy = 5;
add(reset, gc);
reset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
reset.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "pressed");
aField.setText("");
}
});
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore error
}
}
}
編輯該職位。你可能想要的是使用equalsIgnoreCase()方法 – 2012-03-23 10:12:50
非常感謝!我從來不知道equals()之前。乾杯! – 2012-03-23 13:39:34