给面板添加背景图片
給JPanel添加背景圖片:
代碼入下:
1 package test; 2 3 import java.awt.Graphics; 4 import java.awt.Image; 5 6 import javax.swing.ImageIcon; 7 import javax.swing.JPanel; 8 9 public class BackgroundPanel extends JPanel { 10 private int width; 11 private int height; 12 private Image img; 13 14 public BackgroundPanel(String imgPath, int width, int height) { 15 this(new ImageIcon(imgPath).getImage(), width, height); 16 } 17 18 public BackgroundPanel(Image img, int width, int height) { 19 this.width = width; 20 this.height = height; 21 this.img = img; 22 } 23 24 public void paint(Graphics g) { 25 g.drawImage(img, 0, 0, width, height, null); 26 } 27 28 } View Code測試代碼:
?
1 package test; 2 3 import javax.swing.JFrame; 4 import javax.swing.JPanel; 5 6 public class Test { 7 public static void main(String[] args) { 8 final int WIDTH = 600; 9 final int HEIGHT = 600; 10 JFrame frame = new JFrame("測試背景面板"); 11 JPanel panel = new BackgroundPanel("imgPath", WIDTH, HEIGHT); 12 frame.add(panel); 13 frame.setSize(WIDTH, HEIGHT); 14 frame.setVisible(true); 15 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 16 } 17 } View Code?
?
?
轉載于:https://www.cnblogs.com/wss-is-knight/p/3671784.html
《新程序員》:云原生和全面數字化實踐50位技術專家共同創作,文字、視頻、音頻交互閱讀總結
- 上一篇: JAVA笔记18-容器之二增强的for循
- 下一篇: 初次树莓派遇到的一些小问题