gpt4 book ai didi

java - 使用 java swing 删除导致 NullPointerException 的 Pane

转载 作者:行者123 更新时间:2023-11-29 09:53:41 25 4
gpt4 key购买 nike

我正在尝试清除一个 Pane 并使用 swing 将一个新 Pane 放在它的位置。但是根据我当前的设置,它会抛出一个我不理解的 NullPointerException。这是我的代码:

public static void createAndShowGUI() {
final JFrame frame = new JFrame("Generator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel pane1 = new JPanel();
JPanel pane2 = new JPanel();

addComponentsToPane(frame.getContentPane(), pane1, pane2);

frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}

我在 addComponentsToPane 中有一个按钮的 Action 监听器:

    buttonGenerate.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent evt){
Map<String,String> replacements = new HashMap<String,String>(10);
replacements.put("name", textName.getText());

//createTable();
//makeDocx(replacements);
removePane();
}
});

这是 removePane() 函数:

    public static void removePane () {
pane1.removeAll();
}

pane1 已在类的开头声明为 public static JPanel pane1 = null;。当我用 actionlistener 单击按钮时,它会抛出 Exception in thread "AWT-EventQueue-0"java.lang.NullPointerException directed at pane1.removeAll();

为什么会弹出这个错误?我知道我缺少一些重要的东西,有没有人知道它是什么或知道实现我想要的东西的替代方法?

谢谢

最佳答案

不要使用静态变量和方法。那不是设计 GUI 的方法。

也许可以从一个简单的示例开始,例如 How to Use Buttons 上的 Swing 教程中的 ButtonDemo .然后将 instance 变量添加到您可以从监听器访问的类中。

Now when i click the button that removes the pane, it just stays in the click position and nothing happens

当您删除(或添加)组件到可见的 GUI 时,基本代码是:

panel.remove();
panel.revalidate(); // to invoke the layout manager
panel.repaint(); // sometimes needed to force a repaint of the panel

关于java - 使用 java swing 删除导致 NullPointerException 的 Pane ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24247194/

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