java介面編程(6),java介面編程
本文是自己學習所做筆記,歡迎轉載,但請註明出處:http://blog.csdn.net/jesson20121020
可以在JLable或者任何從AbstractButton繼承的組件使用Icon。可以使用任何想用的gif檔案,要開啟一個檔案並且得到圖形,只需要建立一個ImageIcon對象並把檔案名稱傳遞給它即可。然後就可以在程式中使用它了。
下面的例子是給JLabel和JButton添加圖片,並且為按鈕的各個狀態設定不同的圖片,代碼如下:
public class Icons extends JFrame {private static Icon[] icons;private JButton jb,jb2 = new JButton("Disable");public Icons() {setLayout(new FlowLayout());setVisible(true);setSize(400,200);setTitle("Icon");// TODO Auto-generated constructor stubicons = new Icon[]{new ImageIcon(getClass().getResource("icon1.png")),new ImageIcon(getClass().getResource("icon2.png")),new ImageIcon(getClass().getResource("icon3.png")),new ImageIcon(getClass().getResource("icon4.png")),new ImageIcon(getClass().getResource("icon5.png")),new ImageIcon(getClass().getResource("icon6.png"))};jb = new JButton(icons[3]);add(new JLabel(icons[5]));jb.setRolloverEnabled(true);jb.setRolloverIcon(icons[2]);jb.setPressedIcon(icons[2]);jb.setDisabledIcon(icons[4]);jb.setToolTipText("提示");add(jb);jb2.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {// TODO Auto-generated method stubif(jb.isEnabled()){jb.setEnabled(false);jb2.setText("Enable");}else{jb.setEnabled(true);jb2.setText("Disable");}}});add(jb2);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew Icons();}} 執行程式,結果如下:
可以看出,按鈕在按下、禁止、浮動時的顯示的圖片不同,並且,也給按鈕添加了“工具提示”的功能,當滑鼠停留在按鈕上時,就會出現提示的文本,這就使得按鈕具有了相當不錯的動畫效果。
許多不同的Swing組件的構造器都接受Icon類型的參數,也可使用setIcon()來回放或者修改表徵圖。