Need support with JButton events

后端 未结 2 1541
Happy的楠姐
Happy的楠姐 2021-01-16 16:10

I\'ve recently had a question answered about how to open a login panel in my main method in another class. Because i have not yet had any lessons in Swing yet (only basic Ja

2条回答
  •  半阙折子戏
    2021-01-16 16:54

    I've never seen someone Specify an ActionListener for a button quite like that before.. Typically you will do one of two things (AFAIK):

    Implement the ActionListener in the class that contains the JButton you wish to use, then JButton.addActionListener(this) to tell the button to use this class as an ActionListener. Your actionPerformed(ActionEvent e) method will do what you want the button to do.

    OR

    Create a new class that implements the ActionListener class and add it as an actionListener to the JButton.

    Example:

    public class Example1 extends JFrame implements ActionListener
    {
        JButton button1;
        JTextField field1;
    
        public Example1()
        {
            super();
            button1 = new JButton("Login");
            button1.addActionListener(this);
    
            field1 = new JTextField();
    
            add(button1);
            add(field1);
    
        }
    
        @Override
        public void actionPerformed(ActionEvent e)
        {
            if(e.getActionCommand().equals("Login")) //for use with multiple buttons, there are other ways to do this
                field1.setText("LOL");
        }
    
    }
    

    I think this is what you were looking for..

提交回复
热议问题