0
這是我正在開發的閃卡程序。當學習按鈕被按下時,一個字被放置在屏幕的中間,並且該程序假設從用戶輸入的文本字段中讀取並打印它是對還是錯。問題在於程序在按下學習之後正在讀取文本字段,因此在用戶輸入答案之前它將打印爲假。JtextField無法正常工作
有人可以簡要解釋爲什麼這不起作用,我可以做些什麼來解決這個問題?
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
public class NoteCardGUI implements ActionListener {
public static JFrame frame;
public static JPanel panel;
public static JLabel label;
private NoteCard ex;
private JButton study;
public static Box box1 = new Box(), box2 = new Box(), box3 = new Box();
public NoteCardGUI() {
ex = new NoteCard("Hello", "World");
frame = new JFrame("Flash Card");
panel = new JPanel();
study = new JButton("Study");
study.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String resp = NoteCard.getResponse(ex);
String chal = NoteCard.getChallenge(ex);
String a = text.getText();
label = new JLabel(chal, label.CENTER);
label.setAlignmentX(0);
label.setAlignmentY(0);
frame.add(label, BorderLayout.SOUTH);
frame.revalidate();
if(resp.compareTo(a) == 0)
{
label = new JLabel("Correct!");
}
label = new JLabel("Incorrect");
}
});
panel.add(study);
frame.add(panel);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new NoteCardGUI();
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
這是我的NoteCard類,用於需要查看它的人。
public class NoteCard {
public static String challenge;
public static String response;
public String front;
public String back;
public NoteCard(String front, String back) {
this.front = front;
this.back = back;
double a = Math.random();
if (a > 0.5) {
challenge = front;
} else
challenge = back;
if (a < 0.5) {
response = front;
} else
response = back;
}
@Override
public String toString()
{
//return "The challenge:" + challenge + " " + "The response: " + response;
return "The Front: " + front + " " + "The Back: " + back;
}
public static String getChallenge(NoteCard a) {
String chal = a.challenge;
return chal;
}
public static String getResponse(NoteCard a) {
String resp = response;
return resp;
}
public static void main(String[] args) {
NoteCard test = new NoteCard("Ryan", "Hardin");
System.out.println("The challenge: " + getChallenge(test));
System.out.println("The response: " + getResponse(test));
}
}
聽起來就像你用一個按鈕做得太多。如果您必須使用一個按鈕,而不是(例如)替換的「開始學習」按鈕,則在比較之前檢查空字符串。 – ChiefTwoPencils
@Ryan Hardin你可以發佈NoteCard類的代碼嗎?沒有辦法重現您面臨的問題。 – user3437460
@ user3437460是的,只是給我第二個 –