gpt4 book ai didi

java - 单击下一个按钮时显示下一个问题

转载 作者:行者123 更新时间:2023-12-02 05:45:24 25 4
gpt4 key购买 nike

我试图用java读取文件。单击“下一步”按钮时,如何在单击“下一步”按钮时显示第二个问题?

我的.txt文件内容是这样的

1. What is his name
A.John
B.David

2. How old is him?
A.24
B.27

到目前为止,我可以在 JTextField 中显示第一个问题。

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.File;
import java.io.FileReader;


public class NewJFrame extends javax.swing.JFrame {

/**
* Creates new form NewJFrame
*/
public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();
File file = new File("/home/xxx/Desktop/englishQuestion.txt");
StringBuilder sb = new StringBuilder();

try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
if (line.equals("")) {
break;
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
String result = sb.toString();
jTextArea1.setText(result);
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setText("Next");

textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});

label1.setText("Answer:");

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap())
);

label1.getAccessibleContext().setAccessibleName("Answer: ");

pack();
}// </editor-fold>

private void textField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}

最佳答案

我将文件行重构为如下所示:

q1 = What is his name? | John | David
q2 = How old is him? | 24 | 27

这样,每个问题信息都在一行中,更容易解析。您只需将其作为属性文件加载,q1 和 q2 将是键,= 之后的内容将是值。之后,用 | 或您决定使用的任何内容分割它。

我将您的代码重构为如下所示:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;

public class NewJFrame extends javax.swing.JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

private Properties props = new Properties();
private List<Question> questionList = new ArrayList<>();
private int currentQuestionIndex = -1;

private class Question {
private String question;
private String answer1;
private String answer2;

@Override
public String toString() {
return "Question [question=" + question + ", answer1=" + answer1 + ", answer2=" + answer2 + "]";
}

public Question(String question, String answer1, String answer2) {
this.question = question;
this.answer1 = answer1;
this.answer2 = answer2;
}

public String getQuestion() {
return question;
}

public String getAnswer1() {
return answer1;
}

public String getAnswer2() {
return answer2;
}

}

public void showNextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex >= questionList.size()) {
jTextArea1.setText("No more questions available.");
return;
}
jTextArea1.setText("");
Question currentQuestion = questionList.get(currentQuestionIndex);
String newLine = "\n";
jTextArea1.append(currentQuestion.getQuestion() + newLine);
jTextArea1.append("A. " + currentQuestion.getAnswer1() + newLine);
jTextArea1.append("B. " + currentQuestion.getAnswer2());
}

public NewJFrame() throws IOException {
initComponents();
setLocationRelativeTo(null);
pack();

Path path = Paths.get("/home/xxx/Desktop/englishQuestion.txt");
props.load(Files.newInputStream(path));

props.forEach((key, value) -> {
String v = (String) value;
System.out.println(v);
String[] token = v.split("\\|");
String question = token[0];
String answer1 = token[1];
String answer2 = token[2];
Question q = new Question(question, answer1, answer2);
questionList.add(q);
});

showNextQuestion();
}

/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jButton1 = new javax.swing.JButton();
textField1 = new java.awt.TextField();
label1 = new java.awt.Label();
jScrollPane1 = new javax.swing.JScrollPane();
jTextArea1 = new javax.swing.JTextArea();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jButton1.setText("Next");

jButton1.addActionListener(e -> {
showNextQuestion();
});

textField1.setName("\"\""); // NOI18N
textField1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
textField1ActionPerformed(evt);
}
});

label1.setText("Answer:");

jTextArea1.setColumns(20);
jTextArea1.setRows(5);
jScrollPane1.setViewportView(jTextArea1);

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addGap(0, 0, Short.MAX_VALUE)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 53,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 57,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28))
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 421,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
javax.swing.GroupLayout.Alignment.TRAILING,
layout.createSequentialGroup().addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 206,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(label1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(textField1, javax.swing.GroupLayout.PREFERRED_SIZE, 30,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton1))
.addContainerGap()));

label1.getAccessibleContext().setAccessibleName("Answer: ");

pack();
}// </editor-fold>

private void textField1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}

/**
* @param args
* the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed" desc=" Look and feel setting code
// (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the default
* look and feel. For details see
* http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new NewJFrame().setVisible(true);
} catch (IOException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private java.awt.Label label1;
private java.awt.TextField textField1;
// End of variables declaration
}

请注意,我使用 Properties 对象来加载所有键,然后对于每一行,我解析它并创建一个 Question 对象并将其添加到 QuestionList 中。另外,请注意 jButton1.addActionListener(e -> { showNextQuestion(); });。调用 showNextQuestion();方法每次您想要下一个问题时,在本例中,每次单击“下一步”按钮。

我不确定您想通过此应用程序完成什么,目前还不清楚,但我只是回答了您关于如何显示下一个问题的问题。

关于java - 单击下一个按钮时显示下一个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56100044/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com