I have some code that creates a full screen icon in java and sets the background color to pink and the foreground color to red. However every time i run it, it never changes the background color to red but just keeps it see through. I put the code below.
The main java:
import java.awt.*;
import javax.swing.*;
@SuppressWarnings({ "serial" })
public class bob extends JFrame{
public static void main(String[] args) {
DisplayMode dm = new DisplayMode(800,600,16, DisplayMode.REFRESH_RATE_UNKNOWN);
bob b = new bob();
b.run(dm);
}
public void run(DisplayMode dm){
setBackground(Color.PINK);
setForeground(Color.RED);
setFont(new Font("Arial", Font.PLAIN, 24));
screen s = new screen();
try{
s.setFullScreen(dm, this);
try{
Thread.sleep(5000);
}catch(Exception ex){}
}finally{
s.restoreScreen();
}
}
public void paint(Graphics g){
g.drawString("This is gonna be awesome", 200, 200);
}
}
And here is the screen class:
import java.awt.*;
import javax.swing.*;
public class screen2 {
private GraphicsDevice vc;
public screen2(){
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
vc = env.getDefaultScreenDevice();
}
public void setFullScreen(DisplayMode dm, JFrame window){
window.setUndecorated(true);
window.setResizable(false);
vc.setFullScreenWindow(window);
if(dm != null && vc.isDisplayChangeSupported()){
try{
vc.setDisplayMode(dm);
}catch(Exception ex){}
}
}
public Window getFullScreenWindow(){
return vc.getFullScreenWindow();
}
public void restoreScreen(){
Window w = vc.getFullScreenWindow();
if(w != null){
w.dispose();
}
vc.setFullScreenWindow(null);
}
}
anyone have any ideas?
The painting of the background is done in the paint function. So, you have to invoke
super.paint(g)
at the start of the paint function.Also, you need to override the setBackground function.
So the code becomes:
The painting of the background is done in the
paint()
method. Your overrode the method and didn't invokesuper.paint(g)
so the background never gets painted.However, this is NOT the way to do custom painting. You should NOT override the paint() method of a JFrame. If you want to do custom painting then override the
paintComponent()
method of aJPanel
and then add the panel to the frame.Read the section from the Swing tutorial on Custom Painting for more information.
Edit:
Once you add the super.paint(g), child components of the frame will be painted. This means the content pane gets painted and the content pane is painted over the frame so you won't see the background of the frame, so you also need to add: