简体   繁体   English

如何在Frame中添加JPanel

[英]How add JPanel in Frame

In my question, this is Refectoring Class . 在我的问题中,这是Refectoring Class In this class, i'm using JPanel for adding button by a separate Method panel() and Call in the RefectClass Constactor. 在这个类中,我使用JPanel通过单独的Method panel()RefectClass Constactor中的Call来添加按钮。

public class RefectClass extends JFrame {
    JButton btnHome,btnBack;
    JPanel btnContainer;

    public RefectClass(){
        super("Title Here");
        setSize(350,300);
        add(this.panel(),BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

    public void panel(){

        btnContainer=new JPanel();
        btnHome=new JButton("Home");
        btnBack=new JButton("Back");

        btnContainer.add(btnHome);
        btnContainer.add(btnBack);

    }

}

Now how to add panel to JFrame? 现在如何将面板添加到JFrame? it gives an error, when i try to use it. 当我尝试使用它时,它会出错。 I'm unable use to the panel() Mehtod. 我无法使用panel() Mehtod。

Your panel() method returns void - it should return your newly created JPanel instead such that you can add it to the JFrame: 你的panel()方法返回void - 它应该返回你新创建的JPanel,这样你就可以将它添加到JFrame:

public JPanel panel(){

    btnContainer=new JPanel();
    btnHome=new JButton("Home");
    btnBack=new JButton("Back");

    btnContainer.add(btnHome);
    btnContainer.add(btnBack);
    return btnContainer;

}

Let me point out, though, that this is a very unusual approach. 但是,我要指出,这是一种非常不寻常的方法。 You shouldn't have to initialize a member in a public method that returns the newly initialized member when the method is actually just needed inside the class. 您不必在公共方法中初始化成员,该方法在类中实际需要该方法时返回新初始化的成员。 Imagine a client calling the panel method multiple times from outside (since it is public). 想象一下客户端从外部多次调用面板方法(因为它是公共的)。 BtnContainer, btnHOme and BtnBack would be overriden but they wouldn't appear on the screen. BtnContainer,btnHOme和BtnBack将被覆盖,但它们不会出现在屏幕上。 The method seems fairy simply - why not just include it directly in your constructor? 该方法看起来很简单 - 为什么不直接将它包含在构造函数中? Or at least make the method private . 或者至少将该方法private

Your panel() method doesn't return anything so you can't write 您的panel()方法不会返回任何内容,因此您无法编写

add(this.panel(),BorderLayout.CENTER); 添加(this.panel(),BorderLayout.CENTER);

try 尝试

this.panel();
add(this.btnContainer,BorderLayout.CENTER);

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

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