java - JComponent 可见性的奇怪问题
问题描述
我正在使用 Java 中的 Swing 开发一个 GUI 项目,该程序通常运行良好。但是,在每个屏幕下,我都有一个后退按钮,它调用之前屏幕的方法,并通过包含当前屏幕上所有元素的 ArrayList 并在它们上调用 setVisible(false)。运行程序后,如果单击一次后退按钮可以正常工作,但如果返回屏幕并再次单击它,则需要单击两次才能正常工作,然后单击四次,然后单击八次,依此类推。我不知道发生了什么,也不知道为什么会这样,因为我的代码中似乎没有这样做。此外,有时,按钮会正确返回到前一个屏幕,但随后会保持当前屏幕上的组件处于活动状态,就好像从未调用过 setVisible(false) 一样。下面的代码代表了我项目的一般结构。它正在做什么会产生这个问题?
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class MAIN {
static JFrame frame;
static JPanel panel;
public static void main(String [] args) {
mainScreen();
}
public static void mainScreen() {
JButton newScreen = new JButton("Next Screen");
frame = new JFrame();
panel = new JPanel();
panel.setBounds(0,0,1920,1080);
panel.setBackground(Color.cyan);
newScreen.setBounds(50, 500, 100, 500);
newScreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newScreen.setVisible(false);
JButton returnButton = new JButton("return");
returnButton.setBounds(50, 50, 100, 100);
panel.add(returnButton);
returnButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
returnButton.setVisible(false);
mainScreen();
}
});
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel.add(newScreen);
frame.add(panel);
frame.setSize(1920,1080);
frame.setLayout(null);
frame.setVisible(true);
}
}
解决方案
推荐阅读
- javascript - 消息在控制台中安慰两次 - ReeactJS
- python - 交叉熵损失在神经网络中返回无穷大
- ruby - 使用 Nokogiri 打开网站时出现问题 - 请求超时 - 应该归咎于 Etags?
- c# - 迁移 - FOREIGN KEY 约束
- c# - MSUnitTests 上的代理错误,3.1
- android - 我正在尝试在 Android Studio 上发出 POST 请求。但是应用程序停止
- php - 发送到 str_replace PHP 时修改数组键
- ruby-on-rails - Webpacker 在公共/资产中缓慢和重复文件
- java - 为什么在使用正确的数字时我的组件不能正确居中?
- postgresql - 如何检查字符串是否是有效的 postgres 名称?