如何添加类扩展JPanel,并显示自己的面板和按钮?

时间:2014-10-23 07:09:10

标签: java swing jpanel

我在JPanel(jp1)上放了JFrame(fr1),但jp2在哪里?

我想在jp2上的jp1中显示fr1包含内容?

(按钮“start!”和“DEBUGGING”都应显示在窗口上)

怎么办?

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

public class F extends JFrame {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    F fr1 = new F();
    P jp1 = new P();
    jp1.add(new JButton("start!"));
    fr1.setSize(1024, 768);
    fr1.add(jp1, BorderLayout.CENTER);
    fr1.setVisible(true);

    }

}

class P extends JPanel{
    private JPanel jp2;
    private JButton b2;
    public P(){
        jp2 = new JPanel();
        jp2.setBackground(Color.green);
        b2 = new JButton("DEBUGGING.");
        jp2.add(b2);
    }
}

2 个答案:

答案 0 :(得分:4)

在您的类p中使用this.add或仅add将组件添加到jpanel p [class p]。您的类p本身是jpanel,因为它被{{1}扩展因此您需要将jpanel添加到该面板。

并关心jp2 layout panel[class p]你可以通过setLayout ....在class p中设置布局

class P extends JPanel{
    private JPanel jp2;
    private JButton b2;
    public P(){
        jp2 = new JPanel();
        jp2.setBackground(Color.green);
        b2 = new JButton("DEBUGGING.");
        jp2.add(b2);
        // setLayout.....use a appropriate layout if you need
        add(jp2);
    }
}

答案 1 :(得分:2)

您永远不会在jp2中将P添加到任何内容

class P extends JPanel{
    private JPanel jp2;
    private JButton b2;
    public P(){
        jp2 = new JPanel();
        jp2.setBackground(Color.green);
        b2 = new JButton("DEBUGGING.");
        jp2.add(b2);
        //???
    }
}

添加add(jp2);作为最后一个语句