簡體   English   中英

當在 java 中單擊按鈕時,有誰知道如何從其他 class 運行方法

[英]Does anyone know how to run a method form a other class when button is clicked in java

  public class HelpMe{

      GUI window = new GUI();
      // Some code
      public void MyFunction(){
      //Some code
      }
}

在 GUI class 中,我有一個帶有動作偵聽器的按鈕來做某事(該部分有效),所以我在單擊按鈕時運行MyFunction() 那可能嗎。 或者我是否必須做一個接口並覆蓋 function 或其他東西。 先感謝您

好的,我知道你想要的是這樣的東西。

我使用了兩種方法,一種是普通方法,另一種是使用 lambda 表達式。 我希望這有幫助。

package cl.lherrera;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

public class Main {

    public static void main(String[] args) {

        //lambdaApproach();
        statedApproach();

    }

    public static void externalMethod() {
        System.out.println("KEY PRESSED !!");

    }


    public static void statedApproach() {
        JFrame frame = new JFrame("Aplication name");
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JButton myButton = new JButton("Push me");
        panel.add(myButton);
        frame.add(panel);
        frame.setVisible(true);

        ActionListener myEvent = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                Main.externalMethod();

            }

        };

        myButton.addActionListener(myEvent);

    }

    public static void lambdaApproach() {
        JFrame frame = new JFrame("Aplication name");
        frame.setSize(500, 500);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel();
        JButton myButton = new JButton("Push me");
        panel.add(myButton);
        frame.add(panel);
        frame.setVisible(true);

        myButton.addActionListener((ActionEvent e) -> Main.externalMethod());

    }


}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM