简体   繁体   English

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

[英]How to add a class extends JPanel, and display its own panel and button?

I put a JPanel(jp1) on the JFrame(fr1) , but where is jp2 going? 我在JFrame(fr1)上放了一个JPanel(jp1) JFrame(fr1) ,但是jp2会去哪里呢?

I would like to display the jp2 contains in jp1 on fr1 ? 我想在fr1上显示jp1包含的jp2吗?

(the button "start!" and "DEBUGGING" should both displayed on the window) (按钮“开始!”和“调试”应同时显示在窗口上)

How to do? 怎么做?

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);
    }
}

use this.add or just add inside your class p to add component to jpanel p[class p].your class p is itself a jpanel because it is extended by jpanel .so you need to add jp2 to that panel . 使用this.add或者只是add您的P级里面添加组件的JPanel P [P级]。您的P级本身就是一个jpanel ,因为它是由扩展jpanel是.so你需要添加jp2到该面板。

and care about your layout of panel[class p] you can set layout by setLayout.... inside class p 而在乎你的layoutpanel[class p]您可以通过setLayout的设置布局.... 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);
    }
}

You never add jp2 in P to anything 永远不要在P添加jp2

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 add(jp2); 添加add(jp2); as the last statement 作为最后的陈述

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

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