I am currently reading chapter 12 of Head First Java about making GUIs. They have just mentioned that JFrames are split into center, north, south, east and west. The book then uses the 2 argument add() method to add specified components to a specified region with that JFrame.
I can add a JButton to each of the five regions fine. I can also add my own JPanel to the center region with JButtons all around it. But then when I try to add a JPanel to any region other than center, the JPanel does not appear.
I really have searched all over the web and Stack Overflow for the past hour and I have not come across anything that mentions adding JPanels to any region other than center in a JFrame. So my question is: is it possible to add JPanels to the north, south, east or west regions of a JFrame?
Thanks in advance to anyone that can help me with this.
Here is the code that I've been trying to run with my JPanel in the north region:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
public class StackQ {
JFrame frame;
public static void main(String [] args) {
StackQ gui = new StackQ();
gui.go();
}
public void go() {
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("location test");
JButton button2 = new JButton("location test");
JButton button3 = new JButton("location test");
JButton button4 = new JButton("location test");
myDrawPanel custom = new myDrawPanel();
frame.getContentPane().add(button, BorderLayout.CENTER);
frame.getContentPane().add(button2, BorderLayout.EAST);
frame.getContentPane().add(button3, BorderLayout.WEST);
frame.getContentPane().add(button4, BorderLayout.SOUTH);
frame.getContentPane().add(custom, BorderLayout.NORTH);
frame.setSize(300,300);
frame.setVisible(true);
}
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
int red = (int) (Math.random() * 255);
int green = (int) (Math.random() * 255);
int blue = (int) (Math.random() * 255);
Color random = new Color(red, green, blue);
g.setColor(random);
g.fillOval(20,20,100,100);
}
}