java實(shí)現(xiàn)帶有背景圖片的窗體
本文實(shí)例為大家分享了java實(shí)現(xiàn)帶有背景圖片的窗體,供大家參考,具體內(nèi)容如下
將背景圖片添加到面板再添加到窗體
將背景圖片添加到面板上
可設(shè)置背景圖片的畫板
//創(chuàng)建一個(gè)類繼承畫板類public class MyJPanel extends JPanel{ //構(gòu)造方法初始化背景圖片 private Image image; public MyJPanel(Image image){ this.image = image; } //重寫paintComponent方法 @Override public void paintComponent(Graphics g) { //調(diào)用父類paintComponent方法繪制其他組件 super.paintComponent(g); //繪制背景圖片,大小為窗體大小 g.drawImage(image, 0, 0,getWidth(),getHeight(), null); } }
測試
import javax.swing.*;import java.awt.*;//測試類public class Demo1 { //創(chuàng)建窗體 private JFrame myJFrame = new JFrame('有背景圖片'); public Demo1(){ //獲取圖片 Image im = new ImageIcon('forGamesrcresource主題背景.jpg').getImage(); //設(shè)置窗體大小 myJFrame.setSize(889,500); //獲取設(shè)置背景后的面板 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 () { //創(chuàng)建一個(gè)JLayeredPane用于分層的。 JLayeredPane layeredPane=new JLayeredPane(); //獲取圖片 ImageIcon image=new ImageIcon('forGamesrcresource主題背景.jpg'); //JLabel用于存放背景圖片,作為背景添加到JPanel上 JLabel jl=new JLabel(image); //創(chuàng)建JPanel,并將JLabel添加 JPanel jp=new JPanel(); //設(shè)置JPanel大小為背景圖片大小 jp.setBounds(0,0,image.getIconWidth(),image.getIconHeight()); jp.add(jl); //創(chuàng)建測試按鈕 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放到j(luò)p高一層的地方 layeredPane.add(jb1,JLayeredPane.MODAL_LAYER); layeredPane.add(jb2,JLayeredPane.MODAL_LAYER); //設(shè)置窗體 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 (); }}
效果圖
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. python爬蟲實(shí)戰(zhàn)之制作屬于自己的一個(gè)IP代理模塊2. python實(shí)現(xiàn)讀取類別頻數(shù)數(shù)據(jù)畫水平條形圖案例3. 如何理解PHP核心特性命名空間4. Android Studio設(shè)置顏色拾色器工具Color Picker教程5. python 利用toapi庫自動(dòng)生成api6. python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明7. python中PyQuery庫用法分享8. Android Studio 2.0 功能介紹9. Springboot設(shè)置默認(rèn)訪問路徑方法實(shí)現(xiàn)10. 小技巧處理div內(nèi)容溢出
