简体   繁体   English

如何将JPanel作为参数传递给方法?

[英]How can I pass a JPanel as a parameter to a method?

Let me ask. 让我来问。 I´m working in a java project in Netbeans. 我正在Netbeans中的一个Java项目中工作。 I've created a JFrameForm (Design mode), inside the JFrameForm, there is five (5) JPanel. 我创建了一个JFrameForm(设计模式),在JFrameForm中,有五(5)个JPanel。

I've found a method por enable/disable all components inside a Jpanel. 我发现了一种启用/禁用Jpanel内部所有组件的方法。 Works. 作品。

private void changeState(){
    for(Component c : mypanel.getComponents()){
        c.setEnabled(false);
    }
}
//mypanel it's one of a five panels in JFrameForm.
//I would like pass all the JPanel as parameters

I'm try writing a method where I can pass like parameter, just, the JPanel that I need when I invoced the method. 我正在尝试编写一个方法,在该方法中我可以像调用参数一样传递我需要的JPanel。 Can you help me? 你能帮助我吗?

I'm try this,but don't work: 我正在尝试,但是不起作用:

private void changeState(JPanel p){
    for(Component c : p.getComponents()){
        c.setEnabled(false);
    }
}

I'm sorry if the answer it's very easy. 很抱歉,答案很简单。 I'm beginner in JAVA and in this community. 我是JAVA和这个社区的初学者。 I hope you can help me. 我希望你能帮助我。

But it does work! 但这确实有效! When I run the following code (with your method included) it gives me 2 x true, and then 2 x false. 当我运行以下代码(包括您的方法)时,它给我2 x true,然后2 x false。 So the method is fine. 因此该方法很好。

public class Panelik extends JFrame {
    JPanel panel;
    JLabel label1, label2;

    public Panelik() {
        panel = new JPanel();
        label1 = new JLabel();
        label2 = new JLabel();
        panel.add(label1);
        panel.add(label2);

        System.out.println(label1.isEnabled());
        System.out.println(label2.isEnabled());

        changeState(panel);

        System.out.println(label1.isEnabled());
        System.out.println(label2.isEnabled());
    }

    public void changeState(JPanel p) {
        for(Component c : p.getComponents()) {
            c.setEnabled(false);
        }
    }

    public static void main(String[] args) {
        Panelik panelik = new Panelik();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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