繁体   English   中英

如何在ActionListener中将.getSource()与多个JButton一起使用

[英]How to use .getSource() with multiple JButtons in ActionListener

基本上是一个具有几个整数的对象。 我希望int在按下它们各自的按钮时发生变化。 例如,如果您按下JButton 2,则第二个int应该根据actionPerformed方法中if语句中的方法进行更改。 不知道我做错了什么,但是按钮现在绝对不起作用。

public class Object {

    public int someInt;
    //public int someOtherInt;
    //etc. I have a few different ints that I do the same thing with throughout the code, each JButton changes a different int

    public Object() {

        this.someInt = someInt;

        JFrame frame = new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(3);
        frame.setSize(325, 180);
        frame.setVisible(true);
        frame.setTitle("Title");

        //String message = blah blah
        JLabel confirmMessage = new JLabel(message);
        JButton button1 = new JButton("1");
        JButton button2 = new JButton("2");
        JButton button3 = new JButton("3");

        //creating action listener and adding it to buttons and adding buttons to frame

    }

    public class listen implements ActionListener {

        private int someInt;
        private int someOtherInt;

        public listen(int someInt, int someOtherInt) {

            this.someInt = someInt;
            this.someOtherInt = someOtherInt;
        }

        public void actionPerformed() {
            if (aE.getSource() == button1) {
                //change someInt
            }
            //same thing for other buttons
        }
    }
}

将单独的侦听器附加到每个按钮是标准做法:

// syntax for Java 1.8:
button1.addActionListener(e -> {
  // do whatever
});

// syntax for Java 1.7 and earlier:
button1.addActionListener(new ActionListener() {
  public void actionPerformed(ActionEvent e) {
    // do whatever
  }
});

定义动作命令并将其设置为所有按钮。 然后在actionPerformed使用它们来确定单击了哪个按钮。

public class Object {

    private static final String FIRST_ACTION = "firstAction";
    private static final String SECOND_ACTION = "firstAction";


    public Object() {

        JButton button1 = new JButton("1");
        button1.setActionCommand(FIRST_ACTION);

        JButton button2 = new JButton("2");
        button2.setActionCommand(SECOND_ACTION);

        JButton button3 = new JButton("3");

        // creating action listener and adding it to buttons and adding buttons
        // to frame

    }

    public class listen implements ActionListener {

        //some code

        public void actionPerformed(ActionEvent aE) {
            if (aE.getActionCommand().equals(FIRST_ACTION)) {
                // change someInt
            } else if (aE.getActionCommand().equals(SECOND_ACTION)) {

            }
            // same thing for other buttons
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM