Reputation: 39
Alright, I'm not very familiar with the awt api so this is pretty new stuff to me. I have these methods running from my main class to create my jframe. Under my createframe method the background color does not seem to be applied to the frame. Any help?
Here's my frame class
import java.awt.Color;
import java.awt.Container;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class FrameClass {
JFrame frame;
public FrameClass(String framename) {
frame = new JFrame(framename);
}
public void CreateFrame() {
Color c = new Color(0,255,0);
Container con = frame.getContentPane();
con.setBackground(c);
frame.getContentPane().setBackground(c);
frame.setSize(400, 250); // Set the JFrame size when it is on the login screen
frame.setLocationRelativeTo(null); // Center the JFrame
/* Display the frame */
frame.setVisible(true);
}
public void AddPanel() {
JPanel ButtonsPanel = new JPanel();
ButtonsPanel.setVisible(true);
frame.add(ButtonsPanel);
}
}
And here's my main class
public class Admin {
public static FrameClass FrameObject = new FrameClass("ITWebKit Admin Panel");
public static Database DatabaseObject = new Database();
public static void main(String args[]) {
FrameObject.CreateFrame();
FrameObject.AddPanel();
}
}
Upvotes: 1
Views: 1160
Reputation: 208984
Your ButtonsPanel
is covering up the frame's content pane (of which you set the background to). You can either set the ButtonsPanel
's opaque
property to false
or set the background to the ButtonsPanel
instead.
Why this happens
The content pane by default has a BorderLayout
. The BorderLayout
will stretch the ButtonPanel
to fit it's size. If you were to to change the layout manager of the content pane/frame to FlowLayout (which will not stretch the panel), you will see the background.
Other Notes:
FrameObject.CreateFrame(); FrameObject.AddPanel();
. This will set the frame visible before adding the components. Generally you want to add the components, then set the frame visible.
Follow Java naming convention. Method name and variable names begin with lower case letters.
Swing programs should be started on the Event Dispatch Thread (EDT). See Initial Threads
Upvotes: 1