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);
}
}
setVisible(true);
last, after you have created your UI 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... JFrame
(especially since you've already got an instance field of JFrame
), this only makes it more confusing... 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.