首页 > 解决方案 > 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);



     }


      }

标签: javaswingjpaneljbutton

解决方案


推荐阅读