2014-11-30 15:51:40|?次阅读|上传:wustguangh【已有?条评论】发表评论
关键词:Java, Swing, 界面设计|来源:唯设编程网
为了使我们的应用程序界面更加美观,Swing默认提供的JPanel往往无法满足我们的要求,这时候我们可以考虑给JPanel增加背景图片。本实例提供的方法是对JPanel进行重载,在对应的paintComponent函数中diaoy实现背景图的绘制。
package Test; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; /** * test setting JPanel's background * */ public class TestImgJpanel extends JFrame { private Dimension frameSize = new Dimension(600, 600); public TestImgJpanel() { this.setLayout(new BorderLayout()); this.setSize(frameSize); JPanel panel = new JPanel() { @Override protected void paintComponent(Graphics g) { ImageIcon icon = new ImageIcon("D://test.jpg"); Image img = icon.getImage(); g.drawImage(img, 0, 0, icon.getIconWidth(), icon.getIconHeight(), icon.getImageObserver()); } }; this.add(panel, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setVisible(true); } public static void main(String[] args) { TestImgJpanel test = new TestImgJpanel(); } }
paintComponent是JComponent定义的成员方法,用来完成组件的绘制,在需要重新定义外观的组件重载,你需要在该方法中添加你自己的绘制代码。