简体   繁体   中英

Trying to add multiple JPanel to JFrame

I am trying to add these two JPanel to JFrame , however only frame shows and nothing is added. Anyone can help me that what am I missing to add these panels?

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

public class grid_Base extends JFrame {

    JFrame mainp = new JFrame();
    JPanel p = new JPanel();
    JPanel p2 = new JPanel();
    clickButtons buttons[] = new clickButtons[100];

    public grid_Base() {

        super("Battleship");
        mainp.setSize(800, 1500);
        mainp.setResizable(true);
        mainp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainp.setVisible(true);

        p.setLayout(new GridLayout(10, 10));
        for (int i = 0; i < 100; i++) {
            buttons[i] = new clickButtons();
            p.add(buttons[i]);
        }
        mainp.add(p);

        p2.setLayout(new GridLayout(10, 10));
        for (int i = 0; i < 100; i++) {
            buttons[i] = new clickButtons();
            p2.add(buttons[i]);
        }
        mainp.add(p2);

    }
}
  1. Always call setVisible(true); last, after you have created your UI
  2. JFrame uses a BorderLayout as it's default layout, so using mainp.add(p) and then mainp.add(p2) will hide p , as only p2 will be laid out...
  3. Don't extend from JFrame (especially since you've already got an instance field of JFrame ), this only makes it more confusing...
  4. Have a read through Code Conventions for the Java TM Programming Language , it will make it easier for people to read your code and for you to read others
  5. Your second loop is overwriting the contents generated by the first loop, this means that when you try and find a button from the array, you will only be able to find buttons created in the second loop and not the first....

You could make these changes to your code so you can see the panels. Change the values ​​to your requirement.

    mainp.getContentPane().setLayout(null); //<=== New line
    p.setLayout(new GridLayout(10, 10));
    p.setBounds(10,10,390,1300); //<=== position of panel1
    p.setBorder(BorderFactory.createTitledBorder("Panel1")); // border
    mainp.add(p);
    ....
    p2.setLayout(new GridLayout(10, 10));
    p2.setBounds(400,10,380,1300); //<=== position of panel2
    p2.setBorder(BorderFactory.createTitledBorder("Panel2")); //border        
    mainp.add(p2);

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