gpt4 book ai didi

java - 在 actionListener 中将 JPanel 添加到 contentPane

转载 作者:行者123 更新时间:2023-11-29 03:23:40 25 4
gpt4 key购买 nike

我试图在 actionListener 方法中将 JPanel 添加到我的 JFrame,但它仅在第二次单击按钮后出现。这是我的代码的一部分,其中 panCours 是一个 JPanelConstituerData 是目标 JFrame :

addCours.addActionListener(new ActionListener() {

@Override
public void actionPerformed(ActionEvent arg0) {
panCours.setBounds(215, 2, 480, 400);
panCours.setBorder(BorderFactory.createTitledBorder("Saisir les données concernant le cours"));
ConstituerData.this.getContentPane().add(panCours);
}
});

我不明白为什么一点击按钮就没有出现。关于如何解决这个问题的任何解释和帮助?

最佳答案

您需要添加对 repaint(); 的调用(可能还有 revalidate();)以使 JPanel 立即显示。下面的一个基本示例演示了您的问题(和解决方案);

public class Test {

public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);

JButton button = new JButton("Test");
button.setBounds(20, 30, 100, 40);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
JPanel panel = new JPanel();
panel.setBackground(Color.red);
panel.setBounds(215, 2, 480, 480);
frame.add(panel);
frame.revalidate(); // Repaint here!! Removing these calls
frame.repaint(); // demonstrates the problem you are having.

}
});

frame.add(button);
frame.setSize(695, 482);
frame.setVisible(true);

}
}

上面说,(正如其他人所建议的)我建议将来不要使用 null 布局是正确的。 Swing 布局一开始有点尴尬,但从长远来看,它们会对你有很大帮助。

关于java - 在 actionListener 中将 JPanel 添加到 contentPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22210050/

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