简体   繁体   中英

add a object of a class extends jpanel in a frame in same class

i'm trying to make a class that when we make an object of this class in main method show a window with cyan color

in my last programs i wrote a class extends jpanel (example: Test extends JPanel ) and then in main class i just add a object of Test in a Frame but now i wanna do it in Test

generally just with making an object of Test class i want to see a cyan window here is my incomplete code :

public class BoardFrame extends JPanel {    
    private int rowNumber,columnNumber;
    private JFrame mainFrame;   
    public BoardFrame(int m,int n){ 
        rowNumber = m;
        columnNumber = n;           
        mainFrame = new JFrame();           
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setVisible(true);         
    }


    public void paintComponent(Graphics g){
        super.paintComponent(g);
        g.setColor(Color.cyan);         
    }
}

All you have to do is mainFrame.add(this); before you do mainFrame.setVisible(true);

If you want to use the g.setColor(Color.cyan); , you have to draw something.

Use g.fillRect(0, 0, this.getWidth(), this.getHeight());
Or you can just use this.setBackground(Color.cyan); in the constructor.

Here is your complete fixed code. Try it out!

public class BoardFrame extends JPanel {

    public static void main(String[] args) {
        new BoardFrame();
    }

    private int rowNumber, columnNumber;
    private JFrame mainFrame;

    public BoardFrame(int m, int n) {
        rowNumber = m;
        columnNumber = n;
        mainFrame = new JFrame();
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //this.setBackground(Color.cyan); // replaces need for paintComponent
        mainFrame.add(this); // <-- added this line
        mainFrame.setVisible(true);
    }

    public void paintComponent(Graphics g) {
        g.setColor(Color.cyan);
        g.fillRect(0, 0, this.getWidth(), this.getHeight()); // <-- added this line
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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