java實現帶有背景圖片的窗體
本文實例為大家分享了java實現帶有背景圖片的窗體,供大家參考,具體內容如下
將背景圖片添加到面板再添加到窗體
將背景圖片添加到面板上
可設置背景圖片的畫板
//創建一個類繼承畫板類public class MyJPanel extends JPanel{ //構造方法初始化背景圖片 private Image image; public MyJPanel(Image image){ this.image = image; } //重寫paintComponent方法 @Override public void paintComponent(Graphics g) { //調用父類paintComponent方法繪制其他組件 super.paintComponent(g); //繪制背景圖片,大小為窗體大小 g.drawImage(image, 0, 0,getWidth(),getHeight(), null); } }
測試
import javax.swing.*;import java.awt.*;//測試類public class Demo1 { //創建窗體 private JFrame myJFrame = new JFrame('有背景圖片'); public Demo1(){ //獲取圖片 Image im = new ImageIcon('forGamesrcresource主題背景.jpg').getImage(); //設置窗體大小 myJFrame.setSize(889,500); //獲取設置背景后的面板 MyJPanel myJPanel = new MyJPanel(im); //添加按鈕測試 myJPanel.add(new JButton('hello')); myJPanel.add(new JButton('hello1')); myJFrame.add(myJPanel); myJFrame.setLocationRelativeTo(null); myJFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myJFrame.setVisible(true); } public static void main(String[] args) { new Demo1(); }}
效果圖
將背景圖片添加到窗體
分層添加
import javax.swing.*;public class MyJFrame extends JFrame { public MyJFrame () { //創建一個JLayeredPane用于分層的。 JLayeredPane layeredPane=new JLayeredPane(); //獲取圖片 ImageIcon image=new ImageIcon('forGamesrcresource主題背景.jpg'); //JLabel用于存放背景圖片,作為背景添加到JPanel上 JLabel jl=new JLabel(image); //創建JPanel,并將JLabel添加 JPanel jp=new JPanel(); //設置JPanel大小為背景圖片大小 jp.setBounds(0,0,image.getIconWidth(),image.getIconHeight()); jp.add(jl); //創建測試按鈕 JButton jb1=new JButton('hello'); jb1.setBounds(100,100,100,100); JButton jb2=new JButton('hello1'); jb2.setBounds(500,100,100,100); //將jp放到JLayeredPane的最底層 layeredPane.add(jp,JLayeredPane.DEFAULT_LAYER); //將jb放到jp高一層的地方 layeredPane.add(jb1,JLayeredPane.MODAL_LAYER); layeredPane.add(jb2,JLayeredPane.MODAL_LAYER); //設置窗體 this.setLayeredPane(layeredPane); this.setSize(image.getIconWidth(),image.getIconHeight()); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { new MyJFrame (); }}
效果圖
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
1. php測試程序運行速度和頁面執行速度的代碼2. ASP中常用的22個FSO文件操作函數整理3. 三個不常見的 HTML5 實用新特性簡介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析5. ASP調用WebService轉化成JSON數據,附json.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創建項目的過程8. 無線標記語言(WML)基礎之WMLScript 基礎第1/2頁9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執行過程解析10. php網絡安全中命令執行漏洞的產生及本質探究
