So guys I want to use the code I have to set the background of the jFrame without adding anything from another class (like using this code in a jPanel then adding that panel to a jFrame). I wanna do everything in this class. I really have no idea what to do, so I tried this out but this code is not displaying the image!
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class panel extends JFrame{
Image img;
public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
g.dispose();
}
public panel(){
img=new ImageIcon(getClass().getResource("bg_login.jpg")).getImage();
setExtendedState(JFrame.MAXIMIZED_BOTH);
pack();
setVisible(true);
}
public static void main(String[] args){
new panel();
}
}
there is no paintcomponent()
method for jframe
as it's not a jcomponent but a container .you can make a panel and overide paintcomponent
method then setcontentpane
of jframe
to that panel
example
public class panel extends JPanel {
Image img;
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, getWidth(), getHeight(), null);
}
// g.dispose();
}
public panel() {
img=new ImageIcon(getClass().getResource("bg_login.jpg")).getImage();
}
public static void main(String[] args) {
JFrame jFrame = new JFrame();
jFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
panel panel = new panel();
jFrame.setContentPane(panel);
jFrame.pack();
jFrame.setVisible(true);
}
}
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.