简体   繁体   中英

Change Background Color and Icon in JFrame

public class Board {

 static JFrame frame = new JFrame("");


 public static void Board() {

    ImageIcon img = new ImageIcon("icon.png");
    frame.setIconImage(img.getImage());

    frame.setSize(350, 350);
    frame.setResizable(false);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setBackground(Color.BLUE);
    frame.setVisible(true);

}

public class Main {
 public static void main(String[] args) {
    Board.Board(); 
 }
}

It was supposed that the icon in the top left corner changed to my icon.png, and the background should be blue, but it's not happening... what am i doing wrong ?

To set the background of the frame to BLUE you have to replace this line frame.setBackground(Color.BLUE); by this one frame.getContentPane().setBackground(Color.BLUE);

I put the picture in a package like this :

图标图像

And to set the IconImage , I have to retrieve the URL of the picture and create the ImageIcon from the URL like this :

URL iconURL = TestSO.class.getResource("/testso/image.png");
ImageIcon icon = new ImageIcon(iconURL);
frame.setIconImage(icon.getImage());

Maybe it's a bad method to put a picture in package... But I think it works.

尝试更改frame.getContentPane()的颜色

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM