JFrame currentFrame = (JFrame) SwingUtilities.getWindowAncestor((Component) e.getSource());怎么用
时间: 2024-03-21 08:44:40 浏览: 62
这行代码的作用是获取当前事件源所在的 JFrame 对象。具体使用方法可以根据具体需求进行调用。
例如,如果你想在按钮的事件处理方法中关闭当前所在的 JFrame,你可以这样写:
```
JFrame currentFrame = (JFrame) SwingUtilities.getWindowAncestor((Component) e.getSource());
currentFrame.dispose(); // 关闭当前 JFrame
```
或者,如果你想获取当前 JFrame 的标题,可以这样写:
```
JFrame currentFrame = (JFrame) SwingUtilities.getWindowAncestor((Component) e.getSource());
String title = currentFrame.getTitle(); // 获取当前 JFrame 的标题
```
相关问题
怎么在事件监听方法里让弹出下一个jframe的同时上一个jframe自动关闭
在事件监听方法里关闭当前 JFrame 并打开下一个 JFrame 的方法与之前的示例代码类似。下面是一个实现示例:
```
// 获取当前 JFrame 实例
JFrame currentFrame = (JFrame) SwingUtilities.getWindowAncestor((Component) e.getSource());
// 关闭当前 JFrame
currentFrame.dispose();
// 打开下一个 JFrame
NextJFrame nextFrame = new NextJFrame();
nextFrame.setVisible(true);
```
在上面的示例代码中,我们首先通过 getSource() 方法获取事件源组件,然后将其转换为 JFrame 实例。接着,我们调用 dispose() 方法关闭当前 JFrame,并打开下一个 JFrame。这样,在事件监听方法里就可以实现关闭当前 JFrame 并打开下一个 JFrame 的功能了。
● A menu including Open and Exit where Open starts a JFileChooser to select the file with the questions inside and Exit ends the programme. ● Once a file is loaded, the GUI should display one question and its answers at a time. ● The user should be able to select an answer and they should be informed if they were correct or not. ● The user should be made aware of the number of correctly answered and the total number of questions answered. ● The user should only be able to proceed to the next question once they answered the current one. ● Once all questions have been answered, the user should be informed of their overall score and that the game has finished. The Open menu item should now be enabled to start a new quiz. Optionally, you can add a restart menu item to redo the current quiz.
下面是一个实现上述功能的Java Swing程序:
```java
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.SwingConstants;
public class QuizGame implements ActionListener {
private JFrame frame;
private JLabel questionLabel;
private List<Question> questions;
private int currentQuestionIndex;
private int numCorrect;
private int numAnswered;
private JRadioButton[] answerButtons;
private JButton nextButton;
private JButton restartButton;
private JFileChooser fileChooser;
public QuizGame() {
frame = new JFrame("Quiz Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
JPanel questionPanel = new JPanel();
questionPanel.setLayout(new BorderLayout());
questionLabel = new JLabel();
questionLabel.setHorizontalAlignment(SwingConstants.CENTER);
questionPanel.add(questionLabel, BorderLayout.CENTER);
JPanel answerPanel = new JPanel();
answerPanel.setLayout(new BorderLayout());
JPanel buttonPanel = new JPanel();
nextButton = new JButton("Next");
nextButton.addActionListener(this);
buttonPanel.add(nextButton);
restartButton = new JButton("Restart");
restartButton.addActionListener(this);
buttonPanel.add(restartButton);
answerPanel.add(buttonPanel, BorderLayout.SOUTH);
answerButtons = new JRadioButton[4];
for (int i = 0; i < answerButtons.length; i++) {
answerButtons[i] = new JRadioButton();
answerPanel.add(answerButtons[i], BorderLayout.NORTH);
}
frame.add(questionPanel, BorderLayout.CENTER);
frame.add(answerPanel, BorderLayout.SOUTH);
fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
questions = new ArrayList<Question>();
currentQuestionIndex = -1;
numCorrect = 0;
numAnswered = 0;
setMenu();
setNextEnabled(false);
setFrameVisible(true);
}
private void setMenu() {
MenuBar menuBar = new MenuBar();
Menu fileMenu = new Menu("File");
MenuItem openItem = new MenuItem("Open");
openItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int result = fileChooser.showOpenDialog(frame);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
String[] parts = line.split(";");
String question = parts[0];
String[] answers = parts[1].split(",");
String correctAnswer = answers[0];
Question q = new Question(question, answers, correctAnswer);
questions.add(q);
}
reader.close();
Collections.shuffle(questions);
currentQuestionIndex = -1;
numCorrect = 0;
numAnswered = 0;
setNextEnabled(true);
nextQuestion();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
});
MenuItem exitItem = new MenuItem("Exit");
exitItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
fileMenu.add(openItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setMenuBar(menuBar);
}
private void setFrameVisible(boolean visible) {
frame.setVisible(visible);
}
private void setNextEnabled(boolean enabled) {
nextButton.setEnabled(enabled);
}
private void setRestartEnabled(boolean enabled) {
restartButton.setEnabled(enabled);
}
private void nextQuestion() {
currentQuestionIndex++;
if (currentQuestionIndex < questions.size()) {
Question q = questions.get(currentQuestionIndex);
questionLabel.setText(q.getQuestion());
String[] answers = q.getAnswers();
Collections.shuffle(Arrays.asList(answers));
for (int i = 0; i < answerButtons.length; i++) {
answerButtons[i].setText(answers[i]);
answerButtons[i].setSelected(false);
}
} else {
double score = (double) numCorrect / numAnswered;
String message = "You answered " + numCorrect + " out of " + numAnswered + " questions correctly.\n";
if (score >= 0.9) {
message += "Excellent!";
} else if (score >= 0.7) {
message += "Good job!";
} else if (score >= 0.5) {
message += "Not bad.";
} else {
message += "You need more practice.";
}
questionLabel.setText(message);
setNextEnabled(false);
setRestartEnabled(true);
}
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nextButton) {
if (currentQuestionIndex >= 0) {
Question q = questions.get(currentQuestionIndex);
numAnswered++;
boolean correct = false;
for (int i = 0; i < answerButtons.length; i++) {
JRadioButton button = answerButtons[i];
if (button.isSelected()) {
String answer = button.getText();
if (answer.equals(q.getCorrectAnswer())) {
correct = true;
numCorrect++;
}
break;
}
}
String message = correct ? "Correct!" : "Incorrect!";
questionLabel.setText(message);
}
setNextEnabled(false);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
nextQuestion();
}
});
} else if (e.getSource() == restartButton) {
currentQuestionIndex = -1;
numCorrect = 0;
numAnswered = 0;
setRestartEnabled(false);
setNextEnabled(true);
nextQuestion();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
QuizGame game = new QuizGame();
}
});
}
private class Question {
private String question;
private String[] answers;
private String correctAnswer;
public Question(String question, String[] answers, String correctAnswer) {
this.question = question;
this.answers = answers;
this.correctAnswer = correctAnswer;
}
public String getQuestion() {
return question;
}
public String[] getAnswers() {
return answers;
}
public String getCorrectAnswer() {
return correctAnswer;
}
}
}
```
这个程序使用了Java Swing的JFrame、JLabel、JRadioButton、JButton和JFileChooser来实现一个简单的问答游戏。在菜单中,使用JFileChooser选择包含问题和答案的文件,并将它们加载到List<Question>中。在游戏过程中,使用currentQuestionIndex跟踪当前问题的索引,并使用numCorrect和numAnswered跟踪正确回答的问题的数量和总问题数量。使用JRadioButton显示答案选项,并在用户选择一个选项后检查它是否正确,并显示相应的消息。使用nextButton和restartButton在用户回答问题后控制游戏的流程。最后,使用JOptionPane显示用户的总体分数和游戏结束的消息。
阅读全文