Введите ключ JTextField

У меня есть JTextField с Actionlistener. Теперь я хочу, чтобы он делал определенные вещи, когда я нажимаю ввод. Я использую общий ActionListener, поэтому пытаюсь выполнить getSource для JTextField, но это не работает! Надеюсь, кто-нибудь может помочь.

JTextField txtProductAantal = new JTextField(String.valueOf(WinkelApplication.getBasket().getProductAmount(productdelete)));
            txtProductAantal.setBounds(340, verticalPosition + i * productOffset, 40, 20);
            txtProductAantal.addActionListener(this);
            add(txtProductAantal); 

public void actionPerformed(ActionEvent event) {

        if (event.getSource() == btnEmptyBasket) {
            WinkelApplication.getBasket().empty();
            WinkelApplication.getInstance().showPanel(new view.CategoryList());
        }

        if(event.getSource() == txtProductAantal){
            String productgetal = txtProductAantal.getText();
            txtProductAantal.setText(productgetal);
            WinkelApplication.getInstance().showPanel(new view.Payment());
        }
    }

person DaViDa    schedule 07.01.2013    source источник
comment
1) Чтобы быстрее получить помощь, опубликуйте SSCCE. 2) txtProductAantal.setBounds(..) Используйте макеты, чтобы избежать следующих 17 проблем.   -  person Andrew Thompson    schedule 07.01.2013


Ответы (1)


  • необходимо создать временный Object для сравнения

Например

   public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == btnEmptyBasket) {
           //...........
        } else if (source == txtProductAantal) {
           //........... 
        } else {

        }
    }
  • или есть только JTextFields (избегая instanceof внутри оператора if - else), вы можете напрямую привести объект к JTextField

JTextField source = (JTextField) event.getSource();

РЕДАКТИРОВАТЬ,

  • one from the next adviced 17 problems.

  • please to read suggestion by @Andrew Thompson, again

    • 1) For better help sooner, post an SSCCE.

    • 2) txtProductAantal.setBounds(..)

    • Use layouts to avoid the next 17 problems.

мой код работает так, как я ожидал

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class JTextFieldAndActionListener implements ActionListener {

    private JFrame frm = new JFrame("JTextFieldAndActionListener");
    private JTextField one = new JTextField(10);
    private JTextField two = new JTextField();
    private JTextField three = new JTextField();

    public JTextFieldAndActionListener() {
        one.addActionListener(this);
        two.addActionListener(this);
        three.addActionListener(this);
        frm.setLayout(new GridLayout());
        frm.add(one);
        frm.add(two);
        frm.add(three);
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.setLocation(400, 300);
        frm.pack();
        frm.setVisible(true);
    }

    public void actionPerformed(ActionEvent event) {
        Object source = event.getSource();
        if (source == one) {
            System.out.println("firing from JTextField one");
        } else if (source == two) {
            System.out.println("firing from JTextField two");
        } else if (source == three) {
            System.out.println("firing from JTextField three");
        } else {
            System.out.println("something went wrong");
        }
    }

    public static void main(String[] args) {

        javax.swing.SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                JTextFieldAndActionListener ie = new JTextFieldAndActionListener();
            }
        });
    }
}

print_out меня по клавише ENTER

run:
firing from JTextField one
firing from JTextField two
firing from JTextField three
BUILD SUCCESSFUL (total time: 15 seconds)
person mKorbel    schedule 07.01.2013
comment
Все еще не работает. Я поставил систему на текстовое поле, если, но она просто не реагирует на кнопку ввода. - person DaViDa; 07.01.2013
comment
@DaViDa: Это работает слишком хорошо. Вы можете сами протестировать SSCCE, просмотрев этот ссылка. - person nIcE cOw; 07.01.2013
comment
Я думаю, что что-то еще не так, поэтому это не работает, но спасибо всем за то, что показали мне хороший способ сделать это! - person DaViDa; 07.01.2013