Java - Call Method via JButton

后端 未结 5 1135
生来不讨喜
生来不讨喜 2020-12-31 15:08

How can I call a method by pressing a JButton?

For example:

when JButton is pressed
hillClimb() is called;

I know how to display me

相关标签:
5条回答
  • Here is trivial app showing how to declare and link button and ActionListener. Hope it will make things more clear for you.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    
    public class ButtonSample extends JFrame implements ActionListener {
    
        public ButtonSample() {
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(100, 100);
            setLocation(100, 100);
    
            JButton button1 = new JButton("button1");
            button1.addActionListener(this);
            add(button1);
    
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new ButtonSample();
        }
    
        @Override
        public void actionPerformed(ActionEvent e) {
            String command = e.getActionCommand();
    
            if (command.equals("button1")) {
                myMethod();
            }
        }
    
        public void myMethod() {
            JOptionPane.showMessageDialog(this, "Hello, World!!!!!");
        }
    }
    
    0 讨论(0)
  • 2020-12-31 15:50

    Fist you initialize the button, then add ActionListener to it

    JButton btn1=new JButton();
    
    btn1.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e){
            hillClimb();
       }
    });
    
    0 讨论(0)
  • 2020-12-31 15:53
        btnMyButton.addActionListener(e->{
            JOptionPane.showMessageDialog(null,"Hi Manuel ");
        });
    

    with lambda

    0 讨论(0)
  • 2020-12-31 15:55

    If you know how to display messages when pressing a button, then you already know how to call a method as opening a new window is a call to a method.

    With more details, you can implement an ActionListener and then use the addActionListener method on your JButton. Here is a pretty basic tutorial on how to write an ActionListener.

    You can use an anonymous class too:

    yourButton.addActionListener(new ActionListener() { 
        public void actionPerformed(ActionEvent e) { 
            hillClimb();
        } 
    });
    
    0 讨论(0)
  • 2020-12-31 15:56

    You need to add an event handler (ActionListener in Java) to the JButton.

    This article explains how to do this.

    0 讨论(0)
提交回复
热议问题