arma_best
arma_best

Reputation: 65

How to include JPanel from other class to the main

I have this Other class, and I have made panel inside it. How I can add this panel in Main class(When I run like this I get blank window).

public class Other extends JFrame {

    JTextField input = new JTextField(4);

    public JPanel panel () {
        //JPanel for all
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        //Input panel
        JPanel inputPanel = new JPanel();
        inputPanel.setLayout(null);
        inputPanel.setLocation(50,50);
        inputPanel.setSize(250, 30);
        totalGUI.add(inputPanel);

        input.setSize(100,30);
        input.setLocation(150,30);
        inputPanel.add(input);

        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public Other () {
        super("Guess The Number");
    }
}

This is my main class:

public class Main {

    public static void main (String[] args) {

        Other obj = new Other();
        obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        obj.setSize(300,300);
        obj.setVisible(true);
    }
}

Upvotes: 2

Views: 157

Answers (3)

msrd0
msrd0

Reputation: 8361

You shouldn't access the panel from the Main class at all, there is no need for it. To add your panel to the whole frame, write this into the Other constructor:

setContentPane(panel());

If you want to keep the panel and just add the panel, write this instead:

getContentPane().add(panel());

You could also use this line, but it is still there from AWT and should not be used in a Swing application:

add(panel());

Upvotes: 2

Nicolas Albert
Nicolas Albert

Reputation: 2596

Just add the JPanel to your JFrame on its constructor:

public Other(){
    super("Guess The Number");
    add(panel());
}

Upvotes: 2

CalabashFox
CalabashFox

Reputation: 64

you should call the add function of JFrame object and add the JPanel to it. In your main function, do this after initialization of Other object:

obj.add(obj.panel());

Upvotes: -1

Related Questions