[英]Is it possible to call a different class when a Button is clicked
因此,我有一個帶有JButton
的窗口,稱為“開始”。 我想發生的是,當單擊該按鈕時,它將運行一個我已經創建的單獨的類。 這可能嗎,如果可以,我將如何去做? 感謝你的幫助
這是我到目前為止的
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(//not sure what goes here, i would like to call other class here)
順便說一句,在重要的情況下,另一個正在調用的類正在下降
您(您的類)可以實現ActionListener來在單擊按鈕時進行處理。
public class YourClass implements ActionListener {
public YourClass() {
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(this);
}
public void actionPerformed(ActionEvent arg0) {
// Call other class
}
}
有很多方法可以做到這一點。 如果要使用已經實現ActionListener
另一個類,則可以絕對創建該類的對象,然后這樣插入:
//Another class that you're already created is named MyActionListener
// and implements ActionListener for this example
MyActionListener mal = new MyActionListener();
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(mal);
但是,這可能沒有任何意義,因為您需要引用屬於當前類實例的成員的變量。 在這種情況下,您希望當前類這樣實現ActionListener
:
class MyClass implements ActionListener {
public MyClass() {
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(this);
}
@Override
public void actionPerformed(ActionEvent e) {
//do whatever you need to do here
}
}
this
關鍵字表示您正在引用此類的當前實例。 因此,它將使用您在此類中實現的actionPerformed
方法。 您可以在actionPerformed
方法中實例化其他類的對象,然后照常對該對象進行任何調用,或者如果它是此類的成員,則直接調用該成員的函數。 此外,如果您在第二個類上引用靜態方法,則還可以直接在actionPerformed
方法內調用這些方法。
還有一個選擇,就是使用匿名內部類。 如果您要在單個類中具有多個actionPerformed
方法,而這些方法在不同組件的事件處理程序的注冊之間不共享(即,僅將其用於此單個啟動按鈕),則通常使用此方法。 這是使用該方法的方法:
JButton start = new JButton ("Play");
frame.add(start);
start.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//do whatever you want here for whenever start is clicked
}
});
與其他選項一樣,您也可以在此處的actionPerformed
方法中實例化第二個類,或從另一個類中調用靜態方法。 但是,如果您打算調用位於外部類(在本例中為MyClass
)成員的變量上的方法,則需要使用此語法this.MyOtherClass.method()
。 原因是在這種情況下, this
關鍵字可讓您訪問匿名內部類內部的外部類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.