A JButton เป็นคลาสย่อยของ AbstractButton และสามารถใช้สำหรับการเพิ่มปุ่มที่ไม่ขึ้นกับแพลตฟอร์มในแอปพลิเคชัน Java Swing JButon สามารถสร้าง ActionListener ส่วนต่อประสานเมื่อผู้ใช้คลิกที่ปุ่มก็สามารถสร้าง MouseListener . ได้ และ KeyListener อินเทอร์เฟซ โดยค่าเริ่มต้น เราสามารถสร้าง JButton ด้วยข้อความ และยังสามารถเปลี่ยนข้อความของ JButton ได้ด้วยการป้อนข้อความลงในช่องข้อความแล้วคลิกที่ปุ่ม มันจะเรียก actionPerformed() วิธีการของ ActionListener อินเทอร์เฟซและตั้งค่าข้อความที่อัปเดตในปุ่มโดยเรียก setText(textField.getText()) เมธอดของคลาส JButton
ตัวอย่าง
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JButtonTextChangeTest extends JFrame {
private JTextField textField;
private JButton button;
public JButtonTextChangeTest() {
setTitle("JButtonTextChange Test");
setLayout(new FlowLayout());
textField = new JTextField(20);
button = new JButton("Initial Button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (!textField.getText().equals(""))
button.setText(textField.getText());
}
});
add(textField);
add(button);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JButtonTextChangeTest();
}
} ผลลัพธ์

