Java Swing 基礎:標籤、按鈕與事件處理入門。本站提醒廣大學習愛好者:此文章僅供參考,不一定能完全符合您的需求。以下是完整入門正文
標籤和按鈕或許是圖形介面中最常見的兩種元件,按鈕總是與觸發動作事件有關。
標籤是最簡單的 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(String s)。
常用方法:setLabel、getLabel、setMnemonic、setToolTipText、setEnabled、setRolloverEnabled、addActionListener、removeActionListener。
完整範例:視窗內兩個按鈕 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);
}
}
以上就是本文的全部內容,希望大家能夠喜歡。