1、編輯主窗口類,作為單實例Bean組件。(注解默認單實例,@scope=“singleton”)
package com.yjc.sys.rac; import org.springframework.context.Lifecycle; import org.springframework.stereotype.Component; import javax.swing.*; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; /** * @author YQA_Administrator * @date 2021/12/13 13:53 * @value jf 窗體對象 * @value jl 展示標簽 */ @Component public class MainWin extends JFrame { Container container = null; JLabel jl = null; URL url = MainWin.class.getResource("/images/teamcenter_app_32.gif"); public MainWin() { container = this.getContentPane(); jl = new JLabel("這是一個JFrame窗體"); //使標簽上的文字居中 jl.setHorizontalAlignment(SwingConstants.CENTER); //將標簽添加到容器中 container.add(jl); //設置容器的背景顏色 container.setBackground(Color.white); //設置窗體大小 this.setSize(700, 500); //設置窗體關閉方式
//1.不做任何反應。 * 2.僅僅隱藏。 * 3.關閉窗口。 * 4.關閉窗口,並結束所有線程。 * 注意:默認是2,你會發現窗口雖然不見了,但在任務管理器中還存在,這將導致springIoc容器不能自動清理關閉 this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); ImageIcon icon = new ImageIcon(url); // 為標簽設置圖片 jl.setIcon(icon); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { super.windowClosing(e); System.out.println("管理"); //do something }; }); init(); } public void init() { //設置圖標 setIcon(); //使窗體可視 this.setVisible(true); } void setIcon() { Image icon = Toolkit.getDefaultToolkit().getImage(url); this.setIconImage(icon); } }
2、利用SpringApplicationBuilder工廠,創建builder,調用builder.headless(false)方法,避免啟動報錯。
要注意的是:
1)利用Spring工具快速啟動的方式,SpringApplication.run(RacApplication.class)的方式不能處理jaw相關的類。
2) 一定要為窗體設置關閉方式,setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
package com.yjc.sys; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; /** * @author Administrator */ @SpringBootApplication //@ComponentScan("com.yjc.sys.rac") public class RacApplication { public static void main(String[] args) { SpringApplication.run(RacApplication.class); SpringApplicationBuilder builder = new SpringApplicationBuilder(RacApplication.class); builder.headless(false).run(args); } }