首页 文章

Java GUI - actionListener和actionPerformed

提问于
浏览
-1

我的问题与Java编程,GUI概念有关 . 我想知道我是否在actionListener中注册了多个组件,如JButtons,JRadioButtons,JComboBox和JCheckBox,这意味着我希望这些组件执行一个动作 .

现在,在我的actionPerformed方法中,如何链接所有这些组件以执行操作 . 例如,如果我检查一个JRadioButton,一个JCheckBox和一个JButton,我想在aJLabel中显示一些东西,就像一个总数 .

如何在actionPeformed方法中实现所有这些组件?

感谢你..问候,

2 回答

  • 0

    首选方法是为每个组件创建一个 ActionActionListener ,它将为该组件执行所需的作业 .

    这提供了职责的隔离和分离,如果你做得对,重新使用的可能性( Action 可以应用于 JMenuItemJButton JToolbar 并带有密钥绑定)

    它还可以更容易地替换功能(替换单个 ActionActionListener 作为重写"mega" ActionListener

  • 0

    如何在actionPeformed方法中实现所有这些组件?

    要引用组件,请创建实例变量 .

    要实现 actionPerformed 方法,请创建一个实现 ActionListener 的类;这可以是匿名类或命名类 .

    在这个例子中,我们创建了两个ActionListener作为匿名内部类 .

    Scratch.java

    import javax.swing.*;
    
    public class Scratch extends JFrame {
        JButton button1 = new JButton("Click Me");
        JCheckBox check1 = new JCheckBox("Check Me");
        JRadioButton radio1 = new JRadioButton("Select Me");
        JComboBox<String> combo1 = new JComboBox<String>(new String[] {"Choose Me", "No me!"});
    
        public Scratch() {
            setPreferredSize(new java.awt.Dimension(50, 170));
            setLayout(new java.awt.FlowLayout());
            add(radio1);
            add(check1);
            add(combo1);
            add(button1);
            radio1.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent event) {
                    check1.setSelected(!radio1.isSelected());
                }
            });
            button1.addActionListener(new java.awt.event.ActionListener() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    combo1.setSelectedIndex(combo1.getSelectedIndex() == 0 ? 1 : 0);
                }
            });
            pack();
        }
    
        public static void main(String[] args) {
            new Scratch().setVisible(true);
        }
    }
    

    在此部分示例中, Scratch 类本身是 ActionListener

    public class Scratch extends JFrame
        implements java.awt.event.ActionListener // <- implements ActionListener
    {
        JButton button1 = new JButton("Click Me");
    
        public Scratch() {
            // layout, etc.
            add(button1);
            button1.addActionListener(this); // <- tell button1 to call my actionPerformed()
        }
    
        @Override
        public void actionPerformed(java.awt.event.ActionEvent event) {
            Object component = event.getSource(); // which control was clicked?
            if (component == button1) {
                // do something in response to button1 click event
            }
        }
    }
    

    如上一个示例所示,我们可以使用ActionEvent.getSource()方法来发现触发事件的组件 .

相关问题