簡體   English   中英

關注一個JTextField並執行與之相關的操作

[英]Have Focus on one JTextField and perform an action related to it

我的應用程序有兩個JTextField和一個JButton。

我想要一個代碼片段

  • 如果第一個TextField被聚焦/選中,則按鈕會將其TextField(使用setText方法)設置為1,
  • 如果第二個TextField被聚焦/選中,則按鈕會將其TextField(使用setText方法)設置為1

編輯: 我想做的事情 (numInput,denInput都是JTextFields)

public void actionPerformed(ActionEvent e) {
        String s = e.getActionCommand();                            
        if (numInput.isFocusOwner()) {
            if (s.equals("1")) {
                if (z == 0) {
                    numInput.setText(numInput.getText() + "1");
                } else {
                    numInput.setText("");
                    numInput.setText(numInput.getText() + "1");
                    z = 0;
                }
        }
        else if (denInput.isFocusOwner()) {
            if (s.equals("1")) {
                if (z == 0) {
                    denInput.setText(numInput.getText() + "1");
                } else {
                    denInput.setText("");
                    denInput.setText(numInput.getText() + "1");
                    z = 0;
                }
        }
}

這對我永遠不起作用。

創建一個擴展TextActionAction並將該Action添加到您的按鈕。

TextAction具有getFocusedComponent()方法,該方法將返回具有焦點的最后一個文本組件。

該操作的基本代碼為:

TextAction action = new TextAction("")
{
    @Override
    public void actionPerformed(ActionEvent e)
    {
            JTextComponent textField = getFocusedComponent();
            System.out.println( textField.getText() );
    }
};

僅當表單上只有兩個文本字段時,這才起作用。 如果您有兩個以上,則在單擊按鈕之前,需要添加額外的代碼來驗證焦點是否在兩個文本字段中的任何一個上。

暫無
暫無

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

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