下圖是利用在JButton裡加入panel來做其背景圖片JLabel,字的部份也可以直接使用JLabel add於Panel上,如此一來可以很方便的控制文字及圖片的位置,只是在做運算x與y坐標時會比較麻煩,此方法也可與html-tag互相併用,以達更好的效果。
package yku; import java.awt.Frame; import javax.swing.JButton; import java.awt.BorderLayout; import javax.swing.*; import java.awt.Image; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; public class Label extends Frame { private static final long serialVersionUID = 1L; private JButton jButton = null; private JPanel jPanel = null; /** * This is the default constructor */ public Label() { super(); initialize(); } /** * This method initializes this * * @return void */ private void initialize() { this.setSize(500, 600); this.setTitle("JLabel圖片"); this.add(getJPanel(), BorderLayout.CENTER); // this.add(getJButton1(), BorderLayout.CENTER); // jButton要先加入才能在下層 } /** * This method initializes jButton * * @return javax.swing.JButton */ private JButton getJButton() { if (jButton == null) { jButton = new JButton(); } return jButton; } /** * This method initializes jPanel * * @return javax.swing.JPanel */ private JPanel getJPanel() { if (jPanel == null) { jPanel = new JPanel(); jPanel.setLayout(new BorderLayout()); // 用來畫背景圖 MyPanel panel = new MyPanel(); // 把panel的寬高大小設跟jButton一樣 panel.setPreferredSize(jPanel.getPreferredSize()); // 記得要設Layout為null才會有實際寬高 panel.setLayout(null); yku.tool.Image tool = new yku.tool.Image("/han.png"); try { BufferedImage src = javax.imageio.ImageIO.read(tool .getImageUrl()); Image image = src.getScaledInstance(259, 194, Image.SCALE_SMOOTH); ImageIcon img = new ImageIcon(image); JLabel lab = new JLabel(img); JLabel labText = new JLabel("要輸出的字"); lab.setBounds(100, 100, img.getIconWidth(), img.getIconHeight()); labText.setBounds(0, 0, img.getIconWidth() + 20, img.getIconHeight()); // pan0.add(jPanel); panel.add(labText); panel.add(lab); getJButton().add(panel); jPanel.add(getJButton(), BorderLayout.CENTER); } catch (Exception e) { e.printStackTrace(); } } return jPanel; } /** * This method initializes jButton1 * * @return javax.swing.JButton */ private static class MyPanel extends javax.swing.JPanel { /** * */ private static final long serialVersionUID = 1L; // 物件以下元件重畫,此panel會是個透明panel public void paint(Graphics g) { paintChildren(g); } } public static void main(String args[]) { (new Label()).setVisible(true); } }
附上讀取class目錄檔案的方式,可以直接把圖檔放置在執行的class跟目錄
package yku.tool; public class Image { private String image ; public Image(String image) { this.image = image; } public java.net.URL getImageUrl() { return this.getClass().getResource(image); } public String getImagePath() { return getImageUrl().toString(); } }