Swing學習篇 API之JButton組件,

來源:互聯網
上載者:User

Swing學習篇 API之JButton組件,
按鈕(Jbutton)

Swing中的按鈕是Jbutton,它是javax.swing.AbstracButton類的子類,swing中的按鈕可以顯示映像,並且可以將按鈕設定為視窗的預設表徵圖,而且還可以將多個映像指定給一個按鈕。

在JButton中有如下幾個比較常用的構造方法。

  • JButton(Icon icon): 按鈕上顯示表徵圖。
  • JButton(String text): 按鈕上顯示字元。
  • JButton(String text,Icon icon): 按鈕上既顯示表徵圖又先施字元。

JButton類的方法:

  • setText(String text): 設定按鈕的標籤文本。
  • setIcon(Icon defaultIcon): 設定按鈕在預設狀態下顯示的圖片。
  • setRolloverIcon(Icon rolloverIcon): 設定當游標移動到按鈕上方時顯示的圖片。
  • setPressedIcon(Icon pressedIcon): 設定當按鈕被按下時顯示的圖片。
  • setContentAreaFilled(boolean b): 設定按鈕的背景為同名,當設為fase時表示不繪製,預設為繪製。
  • setBorderPainted(boolean b): 設定為不繪製按鈕的邊框,當設為false時表示不繪製,預設為繪製。

按鈕組件是GUI中最常用的一種組件。按鈕組件可以捕捉到使用者的單擊事件,同時利用按鈕事件處理機制響應使用者的請求。JButton類是Swing提供的按鈕組件,在單擊JButton類對象建立的按鈕時,會產生一個ActionEvent事件。

代碼執行個體:

 1 package jFrameDemo; 2  3 import java.applet.*; 4 import java.awt.*; 5 import java.awt.event.*; 6  7 @SuppressWarnings("all") 8 public class ButtonDemo extends Applet implements ActionListener { 9     String msg = "";10     Button yes,no,undecided;11     12     public void init() {13         yes = new Button("Yes");14         no = new Button("No");15         undecided = new Button("Undecided");16         17         add(yes);18         add(no);19         add(undecided);20         21         yes.addActionListener(this);22         no.addActionListener(this);23         undecided.addActionListener(this);24     }25     26     public void actionPerformed(ActionEvent ee) {27         String str = ee.getActionCommand();28         if (str.equals("Yes")) {29             msg = "您選擇了Yes!";30         }else if (str.equals("No")) {31             msg = "您選擇了No!";32         }else {33             msg = "您選擇了Undecided!";34         }35         repaint();36     }37     38     public void paint(Graphics g){39         g.drawString(msg, 6, 100);40     }41 }

運行效果如下:

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.