簡體   English   中英

如何暫停具有main()的程序,直到按下GUI中的按鈕?

[英]How to pause program having main() until a button from GUI is pressed?

我是Java Swing的新手。 我有兩個Java文件。 一個包含main()的文件是GUI文件。

客戶

class Client
{
    GUI gui;
    public static void main(String args[])
    {
        //.......... do something.......
        gui = new GUI();
        // at thin point I want to have value of gui.s1 ....
        //but main() actually do not wait for the user input.
    }
}

圖形用戶界面

class GUI extends JFrame implements ActionListener
{
    String s1="";

    GUI()
    {
        JTextField t1= new JTextField(20);
        JButton j1= new JButton("submit");
        j1.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e)
    {         
        s1=t1.getText();
    } 
}

請指導我,如果不合適的話,請給我建議您認為應該讀懂的文章。

現在,我正在打電話,所以我無法為您提供代碼方面的幫助,我將盡力讓您理解這個概念:用戶輸入,按鈕單擊是5秒鍾后就會發生的事情,例如30分鍾后就會發生。 所以是的,您有時可以讓主設備進入休眠狀態,並希望有一個輸入,等到.s1得到一個值等等。

但是,我不認為這是正確的做法。 最好使用的方法是在用戶單擊按鈕時調用的回調。 使用接口完成。

好吧,首先,您聲明一個可能名為OnRequestClick的接口,在其中實現onRequestClick(String message); 方法。

消息將是s1的文本。

現在,在GUI類中,創建一個名稱為listener的OnRequestClick類型的新字段,並將其放入構造函數中。

現在,在創建GUI對象的地方,編譯器會要求您提供OnRequestClick的代碼,這樣做就是當用戶按下tbe按鈕時將執行的代碼。

好吧,現在我所說的確實是錯誤的:因為我們沒有對listener.onRequestClick()進行任何調用,所以它不會被解雇

因此,在您的actionPerformed中添加listener.onRequestClick(s1.getText()); 因此在您的主要語言中,您將獲得ebemt和文本。

JOptionPane.showInputDialog(..)替換GUI ,不僅代碼會短很多,而且問題也會得到解決。 例如

import javax.swing.*;

class UserInput {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                String name = JOptionPane.showInputDialog(null, "Name?");
                if (name==null) {
                    System.out.println("Please input a name!");
                } else {
                    System.out.println("Name: " + name);
                }
            }
        };
        // Swing GUIs should be created and updated on the EDT
        // http://docs.oracle.com/javase/tutorial/uiswing/concurrency
        SwingUtilities.invokeLater(r);
    }
}

您可以使用回調機制

我已經在單獨的類中的JFrame此處發布了示例代碼,那么ActionListener呢? 請看一看。

interface Callback {
    void execute(String value);
}

abstract class GUI extends JFrame implements ActionListener, Callback{
     ...
     // do not provide the implementation of `execute` method here

     ...
     public void actionPerformed(ActionEvent e) {
        s1 = t1.getText();
        // now callback method is called
        execute(s1);
     }
}

您的主要課程如下所示:

public static void main(String args[]) {
    gui = new GUI() {

        @Override
        public void execute(String value) {
            System.out.println("Entered value:" + value);
        }
    };
}

暫無
暫無

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

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