JAVA JFrame 窗口图标设置

import java.awt.Image;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

class Frame extends JFrame{
    public Frame() {
        setSize(400,400);       
        addWindowListener(new WindowListener() {

            @Override
            public void windowOpened(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowIconified(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }

            @Override
            public void windowClosed(WindowEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void windowActivated(WindowEvent e) {
                // TODO Auto-generated method stub

            }
        });
    }
}

public class Demo {
    public static void main(String[] args) {
        Frame frame = new Frame();
        //设置窗口图标
        try {
            //注意路径问题  / 表示 从根开始
            String src = "/img/1.png";
            Image image = ImageIO.read(frame.getClass().getResource(src));
            frame.setIconImage(image);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        frame.setVisible(true);

    }

}

JAVA JFrame 窗口图标设置_第1张图片

        Toolkit took = Toolkit.getDefaultToolkit();
        //设置窗口图标
        //要用绝对路径
        Image image = took.getImage("src/img/1.png");       
        setIconImage(image);

你可能感兴趣的:(java)