我有一个欢迎(或菜单)窗口 (JFrame),每个可能的操作都有一些按钮 (JButton)。其中每一个都应该启动一个新窗口并隐藏欢迎窗口。我知道我可以使用 setVisible(false);
来做到这一点。但我还不能让它工作。
这是我的一个代码示例:
_startBtn.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e){
System.out.println("_startBtn pressed");
// Code to hide this JFrame and initialize another
}
我的问题是,如何使用像这样的匿名类来做到这一点?
提前致谢!
最佳答案
我正在为您发布一个示例,希望它能对您有所帮助。
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class windows_test {
JFrame login = null;
JFrame inner_frame = null;
public windows_test() {
login = new JFrame();
login.setBounds(10, 10, 300, 300);
login.setLayout(new BorderLayout());
JButton button = new JButton("Login");
login.add(button, BorderLayout.CENTER);
login.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if (inner_frame == null) {
inner_frame = new JFrame();
}
inner_frame.setLayout(new FlowLayout(FlowLayout.CENTER));
inner_frame.add(new JButton("inner frame"));
inner_frame.setVisible(true);
login.setVisible(false);
inner_frame.setBounds(10, 10, 300, 300);
}
});
}
}
我会建议您使用 jpanel 而不是 jframes,但是您要求提供框架,所以我用它们创建了框架。希望它能帮助你问我是不是哪里错了或者你不明白。
关于java - 在 JButton 中使用匿名 ActionListener 隐藏 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11919824/