我正在尝试在actionListener方法中将JPanel添加到我的JFrame中,但它仅在第二次单击按钮后出现。这是我代码的一部分,其中panCours
是JPanel
并ConstituerData
目标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
布局是正确的。秋千布局一开始有点尴尬,但从长远来看,它们会对您有很大帮助。
答案可以在以下代码片段中找到:您需要revalidate()
内容窗格,而不是重新绘制框架。您可以像这样将所需的任何面板添加到内容窗格。如果将 contentPane 声明为私有字段,则不需要getContentPane()
调用。contentPane 是全局的,因此可以直接从类中的任何位置引用它。请注意如果在初始化之前引用它,可能会抛出NullPointerExeptions
。
public class testframe extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
testframe frame = new testframe();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public testframe() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
contentPane = new JPanel();
setContentPane(contentPane);
JButton btnNewButton = new JButton("New button");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel a = new JPanel();
contentPane.add(a);
contentPane.revalidate();
}
});
contentPane.add(btnNewButton);
}
}