这是我正在制作的闪卡程序。当按下学习按钮时,在屏幕中间放置一个单词,并且程序假定从文本字段中读取用户输入并打印它是对还是错。问题是程序在按下学习后正在读取文本字段,因此在用户输入答案之前打印错误。
有人可以简单解释为什么这不起作用以及我可以采取哪些措施来解决这个问题?
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));
}
}
答案 0 :(得分:0)
首先,您需要在actionPerformed方法之外放置UI初始化语句(您创建标签的语句并将标签添加到框架中), 否则每次单击按钮
时都会重新初始化UI其次,当您实际尝试更新JLabel中的文本时,您正在创建新的JLabel。这不起作用,因为您从未将新创建的JLabel添加到框架中。而是这样做:
library(dplyr)
tt <- data.frame(date = c("June", "05/23/2013"))
tt %>% mutate(Date1 = as.Date(date, format = "%m/%d/%Y"),
Date2 = as.Date(paste0("01-",date,"-2013"), format = "%d-%B-%Y"),
newdate = ifelse(is.na(Date1), Date2, Date1) %>% as.Date(origin = "1970-01-01"))