如何将 WindowListener 添加到外部事件
这是我开发的代码。这是保存并执行我的游戏的每个外部 JFrame 的主程序。 ChooseGender 是一个外部程序,只不过是一个 JFrame 及其组件。
我的目标是当chooseGender执行时,它有2个选项按钮(男性,女性),当用户选择一个时,actionListener会将框架设置为setVisible(false),然后让WindowClosing事件打开下一个JFrame,(chooseRace )。更多帧会发生这种情况,但这 2 个帧用于学习目的。我很感谢您提前提供的帮助。 :)
所以我的问题是,我将如何在这个程序中添加一个 WindowListener 来选择性别,以便我可以关闭它并打开下一个?
package javagame;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Main implements WindowListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new chooseGender().setVisible(true);
}
});
EventQueue.invokeLater(new Runnable() {
public void run() {
new chooseRace().setVisible(false);
}
});
}
This is my code I have developed. This is the main program which holds and executes each external JFrame for my Game. chooseGender is an external program which is nothing but a JFrame and its components.
My goal for this is when chooseGender executes, it has 2 buttons for options (male, female) when the user picks one, an actionListener would set the frame to setVisible(false) and then have a WindowClosing event open the next JFrame, (chooseRace). This would happen for several more frames but these 2 are for learning purposes. I appreciate the help in advance. :)
So my question is, how would I go about adding a WindowListener to chooseGender in this program so I can close it and open the next one?
package javagame;
import java.awt.EventQueue;
import java.awt.HeadlessException;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.JFrame;
public class Main implements WindowListener {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new chooseGender().setVisible(true);
}
});
EventQueue.invokeLater(new Runnable() {
public void run() {
new chooseRace().setVisible(false);
}
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的一种简单方法可能只是使用模态 <代码>JDialogs。
代码将类似于以下内容:
您需要实现类似于以下内容的
WidowListener
:并将该窗口侦听器添加到正确的框架:
并且,每个类都会
扩展< /code>
JDialog
并且在其构造函数中使用setModal(true)
。An easy way to implement this may be just using modal
JDialogs
.The code would be similar to the following:
You would want to implement a
WidowListener
similar to the following:And add that window listener to the correct frame:
And, each of those classes would
extend
JDialog
and, in their constructors usesetModal(true)
.