gpt4 book ai didi

java - 重新初始化组件时,我的事件监听器停止工作

转载 作者:行者123 更新时间:2023-12-02 07:21:07 25 4
gpt4 key购买 nike

我有一个具有不同屏幕的程序(由 JPanels 表示)。每次打开屏幕时,我都会重建该面板,并将其放置在 JFrame 上。

现在,当我第一次构建面板(始终是相同的功能)并按下按钮时,附加到它的代码将运行。当我重建屏幕时,eventSource 将永远不会等于实际的 eventSource

查看代码:

public class NewUserScreen extends JPanel implements MouseListener{
//SButton inherits from Component
SButton sb;

...

public void SetFields(){
removeAll();
revalidate();
repaint();

...

sb = new SButton(new Point(282, 295), "Save");
sb.addMouseListener(this);
add(sb);

...
}

...

@Override
public void mouseReleased(MouseEvent arg0) {
if(arg0.getSource().equals(sb)){
DBManager.addUser(...);
}else{
//So after the 2nd build, it will always run this code :(
ScreenManager.OpenAdminS();
}

}
}

最佳答案

  1. have this program with different screens (represented by JPanels). Every time a screen opens I rebuild that panel, and place it on the JFrame.

  2. Now, when I build the panel for the first time (always the same function) and press a button, the code attached to it will run. When I rebuild the screen the eventSource will never be equal to the actual eventSource.

    • 必须为父级(在您的情况下为JFrame)调用一次(re)validate()repaint(),如下最后的代码行(在完成对容器的所有更改之后)

关于java - 重新初始化组件时,我的事件监听器停止工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14217371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com