2012-03-05 49 views
7

Làm cách nào để gọi phương thức bằng cách nhấn một nút JButton?Java - Phương thức gọi qua JButton

Ví dụ:

when JButton is pressed 
hillClimb() is called; 

tôi biết làm thế nào để hiển thị các thông điệp vv khi nhấn một JButton, nhưng muốn biết nếu nó có thể làm điều này?

Rất cám ơn.

+1

Xem http://docs.oracle.com/javase/tutorial/uiswing/ components/button.html – DNA

Trả lời

9

Nếu bạn biết cách hiển thị tin nhắn khi nhấn một nút thì bạn đã biết cách gọi phương thức khi mở một cửa sổ mới là một cuộc gọi đến một phương thức.

Để biết thêm chi tiết, bạn có thể triển khai ActionListener và sau đó sử dụng phương thức addActionListener trên JButton của bạn. Here là một hướng dẫn khá cơ bản về cách viết một ActionListener.

Bạn có thể sử dụng một lớp vô danh quá:

yourButton.addActionListener(new ActionListener() { 
    public void actionPerformed(ActionEvent e) { 
     hillClimb(); 
    } 
}); 
+3

Vì Java 8 cùng một thứ có thể được viết đẹp hơn nhiều bằng cách sử dụng lambda: 'yourButton.addActionListener (e -> hillClimb());' – Lii

1

Bạn cần phải thêm một event handler (ActionListener trong Java) cho JButton.

This article giải thích cách thực hiện việc này.

4

Đây là ứng dụng tầm thường cho thấy cách khai báo và nút liên kết và Trình chọn hành động. Hy vọng nó sẽ làm cho mọi thứ rõ ràng hơn cho bạn.

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

public class ButtonSample extends JFrame implements ActionListener { 

    public ButtonSample() { 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
     setSize(100, 100); 
     setLocation(100, 100); 

     JButton button1 = new JButton("button1"); 
     button1.addActionListener(this); 
     add(button1); 

     setVisible(true); 
    } 

    public static void main(String[] args) { 
     new ButtonSample(); 
    } 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     String command = e.getActionCommand(); 

     if (command.equals("button1")) { 
      myMethod(); 
     } 
    } 

    public void myMethod() { 
     JOptionPane.showMessageDialog(this, "Hello, World!!!!!"); 
    } 
} 
1

Fist bạn khởi tạo các nút, sau đó thêm ActionListener để nó

JButton btn1=new JButton(); 

btn1.addActionListener(new ActionListener(){ 
    public void actionPerformed(ActionEvent e){ 
     hillClimb(); 
    } 
}); 
0
btnMyButton.addActionListener(e->{ 
     JOptionPane.showMessageDialog(null,"Hi Manuel "); 
    }); 

với lambda

Các vấn đề liên quan