小議如何在組件上顯示圖象

來源:互聯網
上載者:User
顯示 小議如何在組件上顯示圖象

●○●○●○●○●○●○●○●○●○●○●○●○●○●○
○●作者:劉湛○●○日期:2000-12-22●○●jeru@163.net○●
●○●○●○●○●○●○●○●○●○●○●○●○●○●○
○●一天進步一小步●○●○●○●○●○充實我的每一天○●
●○●○●○●○●○●○●○●○●○●○●○●○●○●○

首先要說明的是,在組件上方便的顯示圖象是 swing 比 AWT 優越的特性之一,暫時我還沒看到如何
在 AWT 中實現這一方法,如果你知道,請來信告訴我。

在 swing 中,button, lable 等組件都可輕易的用圖象來改變它的外觀,以 button 為例,當建立一
個 button 對象的時候通常是這樣的:
JButton button = new JButton("Click me");
這樣就建立了一個 button 對象,上面顯示的文字是 Click me.

現在我們來稍做改動:
ImageIcon buttonIcon = new ImageIcon("button.gif", "a background of button");
JButton button = new JButton(buttonIcon);
這兩行代碼就達到了目的,在 button 上顯示了圖象 button.gif,注意我們用的是 ImageIcon 類,而
不是 Image 類。ImageIcon 中的第二個參數是對 ImageIcon 對象的描述,這個參數以後可能會被
assistive 技術用到。

如果想在 button 上同時顯示文字和圖象,還可以這樣:
JButton button = new JButton("Click me", buttonIcon);

另外,還可以定義圖象在 組件上的位置,如:
JButton button = new JButton("Click me", buttonIcon, JButton.CENTER);

最後,在順便的講一下如何改變你的 applet/application 上角的那個小表徵圖,怎麼樣,看那杯咖啡厭煩了把?
讓我們來換上自己的表徵圖吧,我用的是setIconImage方法。
在 applet中,定義了一個image對象後就可以直接以它為參數來使用 setIconImage() 方法了,
而在 application 中,還需要由 ImageIcon 類轉換到 Image 對象去。可能是我笨,不知道如何在application中
有什麼簡單的辦法可以直接使用 Image 類,誰知道請寫信給我,十分感謝。
URL imgURL = getClass().getResource("title.gif");
ImageIcon icon = new ImageIcon(imgURL);    
setIconImage(icon.getImage());


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.