繁体   English   中英

将JPanel添加到actionListener中的contentPane

[英]Add JPanel to contentPane within actionListener

我正在尝试在actionListener方法中将JPanel添加到我的JFrame中,但是它仅在第二次单击按钮后出现。 这是我的代码的一部分,其中panCoursJPanelConstituerData是目标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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM