This question already has an answer here:
Failure to show multiple JPanels [duplicate]
                                
                                    (1个答案)
                                
                        
                                3年前关闭。
            
                    
JPanel将不会显示在JFrame上,我也不知道为什么。看来JPanel并未以某种方式添加到JFrame中。有什么建议么?

import java.awt.*;
import javax.swing.*;

public class LeaseItGUI extends JPanel{
    private int width=600,height=600;

    public void paintComponenet(Graphics g){
        super.paintComponent(g);
        g.fillRect(0, 0, width, height);
    }
}

import javax.swing.*;
import java.awt.*;

public class LeaseItMain extends JFrame{
    private int width=600,height=600;

    public LeaseItMain(){
        setSize(width,height);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        LeaseItGUI theGui = new LeaseItGUI();
        setVisible(true);
        add(theGui);
    }


    public static void main(String[] args){
        LeaseItMain LIM = new LeaseItMain();
    }
}

最佳答案

采用:

add(theGui);


要么

setContentPane(theGui);


之前:

setVisible(true);

07-25 21:11