Swing按鈕組件--JButton

窗體組件類結構
在這裏插入圖片描述
JButton按鈕構造方法

  • JButton():創建不帶有設置文本或圖標的按鈕
  • JButton(Action a):創建一個按鈕,其屬性從所提供的Action中獲取
  • JButton(Icon icon):創建一個帶圖標的按鈕
  • JButton(String text):創建一個帶文本的按鈕
  • JButton(String text,Icon icon):創建一個帶初始文本和圖標的按鈕

Action接口

  • JButton(Action a)中的Action是一個接口
  • public interface Action extends ActionListener
  • 注意:接口可以繼承一個或多個接口

ActionListener接口方法

  • void actionPerformered(ActionEvent e):發生操作時調用

JButton常用方法

  • void addActionListener(ActionListener listener):爲組件註冊ActionListener監聽
  • void setIcon(Icon icon):設置按
  • 鈕的默認圖標
  • void setText(String text):設置按鈕的文本
  • void setMargin(Insets m):設置按鈕邊框和標籤之間的空白
  • void setMnemonic(int menomenic):設置按鈕的鍵盤快捷鍵,所設置的快捷鍵在實際操作是需要結合alt鍵進行實現
  • void setPressedIcon(Icon icon):設置按下按鈕的圖標
  • void setSelectedIcon(Icon icon):設置選擇按鈕時的圖標
  • void setRolloveiicon(Icon icon):設置鼠標移動到按鈕區域時的圖標
  • void setDisabledIcon(設置按鈕無效狀態下的圖標)
  • void setVerticalAlignment(int alig):設置圖標和文本的垂直對齊方式
  • void setHorizontalAlignment(int alig):設置圖標和文本的水平對齊方式
  • void setEnable(boolean flag):啓用或禁用按鈕
  • void setVerticalTextPosition(int textPosition):設置文本相對於圖標的垂直位置
  • void setHorizontalTextPosition(int textPosition):設置文本相對於圖標的水平位置

Demo

import java.awt.Color;
import java.awt.Dimension;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

public class Demo {
	public static void main(String[] args) {
		//創建JFrame對象
		JFrame jf = new JFrame("Java按鈕組件實例");
		//創建JPanel對象
		JPanel jp = new JPanel();
		//創建JButton對象
		JButton b1 = new JButton("我是普通按鈕");
		JButton b2 = new JButton("我是帶背景色的按鈕");
		JButton b3 = new JButton("我是不可用按鈕");
		JButton b4 = new JButton("我是頂部對齊按鈕");
		//向JPanel面板添加按鈕組件
		jp.add(b1);
		//設置按鈕背景色
		b2.setBackground(Color.YELLOW);
		jp.add(b2);
		//設置按鈕不可用
		b3.setEnabled(false);
		jp.add(b3);
		//設置按鈕對齊方式爲頂部對齊
		b4.setVerticalAlignment(SwingConstants.NORTH);
		//設置按鈕大小
		Dimension preferredSize = new Dimension(160,60);
		b4.setPreferredSize(preferredSize);
		jf.add(jp);
		jf.setVisible(true);
		jf.setSize(400,400);
		jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
	}
}

在這裏插入圖片描述
注意

  • setBounds()和setSize()並不是任何情況下都有效
  • 要使用setBounds()和setSize()這類的方法時,要保證所使用的對象的容器(或面板)的佈局必須是null
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章