首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Swing 基礎:標籤、按鈕與事件處理入門

     編輯:Java 相關知識

Java Swing 基礎:標籤、按鈕與事件處理入門。本站提醒廣大學習愛好者:此文章僅供參考,不一定能完全符合您的需求。以下是完整入門正文


標籤和按鈕或許是圖形介面中最常見的兩種元件,按鈕總是與觸發動作事件有關。

標籤 (JLabel)

標籤是最簡單的 Swing 元件。標籤物件的作用是對位於其後的介面元件作解釋。可以設定標籤的屬性,即前景色、背景色、字體等,但不能靜態編輯標籤中的文字。

程式關於標籤的基本內容有以下幾個方面:
1. 宣告一個標籤名;
2. 建立一個標籤物件;
3. 將標籤物件加入到某個容器。

JLabel 常用建構方法:
1. JLabel():建立無顯示文字的標籤;
2. JLabel(String s):建立顯示文字為 s 的標籤;
3. JLabel(String s, int align):建立顯示文字為 s 的標籤,align 為水平對齊方式:JLabel.LEFT、JLabel.CENTER、JLabel.RIGHT。

其他常用方法:setText、getText、setBackground、setForeground。

按鈕 (JButton)

按鈕在介面設計中用於觸發動作事件。按鈕可顯示文字,當按鈕被啟動時,能觸發動作事件。

JButton 常用建構方法:JButton()、JButton(String s)。
常用方法:setLabel、getLabel、setMnemonic、setToolTipText、setEnabled、setRolloverEnabled、addActionListener、removeActionListener。

按鈕處理動作事件基本步驟

  1. 實作 ActionListener 介面;
  2. 宣告按鈕名;
  3. 建立按鈕物件;
  4. 加入容器;
  5. 註冊監聽器:addActionListener(this) 或其他實作類別物件;
  6. 實作 actionPerformed(ActionEvent e) 方法,透過 getActionCommand() 判斷事件來源。

完整範例:視窗內兩個按鈕 Red/Green,點擊切換背景顏色。

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class J503 {
    public static void main(String[] args) {
        ButtonDemo myButtonGUI = new ButtonDemo();
        myButtonGUI.setVisible(true);
    }
}

class ButtonDemo extends JFrame implements ActionListener {
    public static final int Width = 250;
    public static final int Height = 200;
    ButtonDemo() {
        setSize(Width, Height);
        setTitle("按鈕事件範例");
        Container conPane = getContentPane();
        conPane.setBackground(Color.BLUE);
        conPane.setLayout(new FlowLayout());
        JButton redBut = new JButton("Red");
        redBut.addActionListener(this);
        conPane.add(redBut);
        JButton greenBut = new JButton("Green");
        greenBut.addActionListener(this);
        conPane.add(greenBut);
    }
    public void actionPerformed(ActionEvent e) {
        Container conPane = getContentPane();
        if (e.getActionCommand().equals("Red"))
            conPane.setBackground(Color.RED);
        else if (e.getActionCommand().equals("Green"))
            conPane.setBackground(Color.GREEN);
    }
}

以上就是本文的全部內容,希望大家能夠喜歡。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved