2012-03-05 76 views
7

如何通過按JButton來調用方法?Java - 通過JButton調用方法

例如:

when JButton is pressed 
hillClimb() is called; 

我知道如何按一個JButton時顯示的消息等,但想知道是否可以這樣做呢?

非常感謝。

+1

見http://docs.oracle.com/javase/tutorial/uiswing/ components/button.html – DNA 2012-03-05 15:59:20

回答

9

如果您在按下按鈕時知道如何顯示消息,那麼您已經知道如何調用方法,因爲打開新窗口是對方法的調用。

有了更多的細節,你可以實現一個ActionListener,然後在你的JButton上使用addActionListener方法。 Here是一個關於如何編寫ActionListener的基本教程。

您可以使用匿名類太:

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

從Java 8開始,使用lambda可以寫得更漂亮:'yourButton.addActionListener(e - > hillClimb());' – Lii 2015-08-28 09:33:37

1

您需要一個事件處理程序(ActionListener在Java中)添加到JButton

This article解釋瞭如何做到這一點。

4

這裏是一個簡單的應用程序,展示瞭如何聲明和鏈接按鈕和ActionListener。希望它能讓你的事情變得更加清晰。

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

拳初始化按鈕,然後添加的ActionListener它

JButton btn1=new JButton(); 

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

與拉姆達