Java Swing JButton

JButton được dùng để tạo nút nhấn độc lập với nền tảng. Kết quả ứng dụng trong những hành động khi nút Button được nhấn sẽ hiển thị. JButton kế thừa lớp AbstractButton.

Các Constructors hay sử dụng:

Constructor

Mô tả chức năng

JButton()
Constructor JButton() không có tham số

JButton(String text)
Constructor có tham số là nhãn của Button

JButton(Icon icon)
Constructor có tham số là hình nền của Button

JButton(String text,Icon icon)
Constructor có 2 tham số: nhãn Button và hình nền của Button

Ví dụ: Constructor JButton()

package firstexample;

import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author pc
 */
public class FirstExample extends JFrame{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame ui=new JFrame(); //khai báo khung cửa sổ giao diện
        ui.setDefaultCloseOperation(EXIT_ON_CLOSE); //đóng compiler, tiết kiệm vùng nhớ
       JButton btn1=new JButton();
        btn1.setBounds(130,100,100, 40);
        ui.add(btn1);

        ui.setLayout(null);
        ui.setSize(400,300); //kích thước cửa sổ
        ui.setLocationRelativeTo(null); //hiển thị giữa màn hình
        ui.setVisible(true); //hiển thị cửa sổ khi chạy
    }

}

Jbutton_k

Ví dụ: JButton(Icon icon)

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @author pc
 */
public class FirstExample extends JFrame{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        JFrame ui=new JFrame(); //khai báo khung cửa sổ giao diện
        ui.setDefaultCloseOperation(EXIT_ON_CLOSE); //đóng compiler, tiết kiệm vùng nhớ
        //Chèn button có background là icon, chỉ ra đường dẫn chứa hình icon

        JButton btn1=new JButton(new ImageIcon("...\\icon.gif"));
        btn1.setBounds(130,100,100, 40);
        ui.add(btn1);

        ui.setLayout(null);
        ui.setSize(400,300); //kích thước cửa sổ
        ui.setLocationRelativeTo(null); //hiển thị giữa màn hình
        ui.setVisible(true); //hiển thị cửa sổ khi chạy
    }

}

setBounds(int x, int y, int width, int height)

x: vị trí tọa độ trên trục x của màn hình muốn đặt component vào cửa sổ hiện thị

y: vị trí tọa độ trên trục y của màn hình muốn đặt component vào cửa sổ hiện thị

width: độ rộng (chiều dài) của component

height: độ cao (chiều cao) của component

jbutton_icon.PNG

Advertisement

Share this:

Like this:

Like

Loading…