Reputation: 131
This is probably a really stupid error but iv'e just started learning the .awt package. I followed a tutorial to the letter, in the video his window's background is red, there are no errors in my code yet it won't change the background color. Thanks for any help!
import java.awt.Color;
import javax.swing.*;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame f = new JFrame();
f.setVisible(true);
f.setSize(350,350);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("Window");
f.setBackground(Color.RED);
}
}
Upvotes: 2
Views: 10074
Reputation: 109815
1) JFrame
can't do that, you have to change Color
for content pane e.g.
JFrame.getContentPane().setBackground(myColor)
2) You need to wrap GUI related code (in main
method) to the invokeLater
For example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI {
public GUI() {
JFrame frame = new JFrame();
frame.setTitle("Test Background");
frame.setLocation(200, 100);
frame.setSize(600, 400);
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
frame.getContentPane().setBackground(Color.BLUE);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI gUI = new GUI();
}
});
}
}
Upvotes: 10
Reputation: 20061
Instead of
f.setBackground(Color.RED);
call
f.getContentPane().setBackground(Color.RED);
The content pane is what is displayed.
As a side note, here's a JFrame
tip: you can call f.add(child)
and the child will be added to the content pane for you.
Upvotes: 4