[英]Add JPanel to contentPane within actionListener
我正在嘗試在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();
的調用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,而不是重新繪制框架。 您可以像這樣將任何面板添加到內容窗格。 如果將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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.