function mychange(num){ document.getElementById("div1").style.backgroundImage="url("+num+".jpg)"; document.getElementById("div2").style.backgroundImage="url("+num+".jpg)"; }
創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站設(shè)計、成都網(wǎng)站制作與策劃設(shè)計,久治網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:久治等地區(qū)。久治做網(wǎng)站價格咨詢:028-86922220
//?不加包,圖片跟類文件在一個目錄,命令行下編譯執(zhí)行就行了
//?如果建工程,圖片放到工程根目錄
import?java.awt.Container;
import?java.awt.FlowLayout;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
import?javax.swing.ImageIcon;
import?javax.swing.JButton;
import?javax.swing.JFrame;
import?javax.swing.JLabel;
import?javax.swing.JPanel;
public?class?Student?extends?JFrame?{
public?Student()?{
init();
}
private?void?init()?{
final?Container?c?=?getContentPane();
final?JLabel?imgLabel?=?new?JLabel();
JButton?btnPic?=?new?JButton("換背景圖片");
btnPic.addActionListener(new?ActionListener()?{
public?void?actionPerformed(ActionEvent?e)?{
ImageIcon?img?=?new?ImageIcon(System.getProperty("user.dir")?+?"\\a.png");
imgLabel.setIcon(img);
imgLabel.setBounds(0,?0,?img.getIconWidth(),?img.getIconHeight());
}
});
((JPanel)getContentPane()).setOpaque(false);
getLayeredPane().add(imgLabel,?new?Integer(Integer.MIN_VALUE));
setLayout(new?FlowLayout());
add(btnPic);
setSize(500,?500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public?static?void?main(String[]?args)?{
new?Student().setVisible(true);
}
僅僅是給窗口添加背景的話是很簡單的,添加上以下語句(自己去添加變量哈):\x0d\x0a\x0d\x0alabel = new JLabel(background); //background為ImageIcon\x0d\x0a// 把標(biāo)簽的大小位置設(shè)置為圖片剛好填充整個面板 \x0d\x0alabel.setBounds(0, 0, this.getWidth(), this.getHeight());\x0d\x0a//添加圖片到frame的第二層(把背景圖片添加到分層窗格的最底層作為背景)\x0d\x0athis.getLayeredPane().add(label,new Integer(Integer.MIN_VALUE));\x0d\x0a//把內(nèi)容窗格轉(zhuǎn)化為JPanel,否則不能用方法setOpaque()來使內(nèi)容窗格透明\x0d\x0ajPanel=(JPanel)this.getContentPane();\x0d\x0a//設(shè)置透明\x0d\x0ajPanel.setOpaque(false);\x0d\x0a\x0d\x0a然后你上面那個JPanel p也設(shè)置成透明就可以了
import?java.awt.*;
import?java.awt.event.*;
import?javax.swing.*;
public?class?KeyCharEx?extends?JFrame?{
JLabel?la?=?new?JLabel("Enter鍵換背景顏色");
KeyCharEx()?{
super("請按Enter鍵");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new?FlowLayout());
this.add(la);
this.addKeyListener(new?MyKeyListener());//?整個界面添加鍵盤敲擊事件
setSize(250,?150);
setVisible(true);
}
class?MyKeyListener?extends?KeyAdapter?{
public?void?keyTyped(KeyEvent?e)?{//?應(yīng)該是這個方法?keyTyped?鍵盤按下,然后釋放
super.keyTyped(e);
int?r?=?(int)?(Math.random()?*?256);
int?g?=?(int)?(Math.random()?*?256);
int?b?=?(int)?(Math.random()?*?256);
switch?(e.getKeyChar())?{
case?'\n':
la.setText("r="?+?r?+?",g="?+?g?+?",b="?+?b);
getContentPane().setBackground(new?Color(r,?g,?b));
break;
case?'q':
System.exit(0);
}
}
}
public?static?void?main(String[]?args)?{
new?KeyCharEx();
}
}