使用ActionListener实现ItemListener接口

时间:2014-08-16 18:54:27

标签: java swing user-interface actionlistener itemlistener

如果按下ItemListener,我想执行JButton方法(如我的ActionListener方法中所述)。我觉得我错过了一些重要的东西,因为据我所知,你不能在另一种方法中使用方法。

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JOptionPane;

    public class spelling2 extends JFrame {

        private static final long serialVersionUID = 1L;
        JFrame frame = new JFrame();
        JButton question1;
        JButton question2;
        private JCheckBox q1a1;
        private JCheckBox q1a2;
        private JCheckBox q1a3;


        public spelling2() {
        super("Question 1");
        setLayout(new FlowLayout());

        q1a1 = new JCheckBox("recipracate");
        q1a2 = new JCheckBox("reciprocate");
        q1a3 = new JCheckBox("reciprokate");
        add(q1a1);
        add(q1a2);
        add(q1a3);


        question1 = new JButton("Question 1");
        add(question1);

        question2 = new JButton("Question 2");
        add(question2);


        HandlerClass handler = new HandlerClass();
        q1a1.addItemListener(handler);
        q1a2.addItemListener(handler);
        q1a3.addItemListener(handler);
        question1.addActionListener(handler);
        question2.addActionListener(handler);
        }


        private class HandlerClass implements ActionListener, ItemListener {

        public void actionPerformed (ActionEvent event) {
        if (question1.isSelected()) {
            d
        }
        public void itemStateChanged (ItemEvent event) {
        if (q1a2.isSelected())
            JOptionPane.showMessageDialog(frame, "quintessence is the correct answer");
        else if (q1a1.isSelected())
            JOptionPane.showMessageDialog(frame, "That is the wrong answer");
        else if (q1a3.isSelected())
            JOptionPane.showMessageDialog(frame, "That is the wrong answer");

        }
    }
}

1 个答案:

答案 0 :(得分:1)

我希望我对这个问题的解释是正确的,你试图找出哪个按钮被点击了。您可以使用ActionEvent.getSource()来获取发起事件的对象。例如:

@Override
public void actionPerformed(ActionEvent event) {
    if (event.getSource() == question1) {
        JOptionPane.showMessageDialog(frame, "question1 is pressed");   
    } else if (event.getSource() == question2) {
        JOptionPane.showMessageDialog(frame, "question2 is pressed");
    }
}

请注意,您还可以使用匿名操作侦听器,例如:

question1.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        JOptionPane.showMessageDialog(frame, "question1 is pressed");               
    }
});

另请注意,除非您向其添加新功能,否则通常无需扩展顶级窗口(如JFrame)。