Trying to add ActionListener to JButtons

后端 未结 6 1135
忘掉有多难
忘掉有多难 2020-12-21 23:50

I cannot figure out how to add Actionlisteners to the JButtons, any help would be much appreciated.

public class Translator extends         


        
6条回答
  •  轮回少年
    2020-12-22 00:12

    JButton button = new JButton("Button");
    button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            //To-Do
            //Button clicked
            });
    

    Hope this helps, it's relatively simple! You just need to add an ActionListener to your desired JButton

    To give you a broader idea of how to implement it in a case-scenario where I would like to run a new GUI frame after pressing a button:

    startNewFrame.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("Starting new frame");
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        NewFrame newFrame = new NewFrame();
                        newFrame.setVisible(true);
                        dispose();//Disposes of current frame
                    }
                });
            }
        });
    

提交回复
热议问题