how to define action listener for buttons in java

后端 未结 4 549
悲哀的现实
悲哀的现实 2021-01-26 08:31

I have a jframe that includes JButton.I have six buttons in this frame, but I don\'t know how to define action listener for this buttons.please help to solve this probl

4条回答
  •  终归单人心
    2021-01-26 09:02

    Have a look at the Java tutorials on how to use ActionListeners:

    https://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

    Here's a simple example:

        import java.awt.BorderLayout;
        import java.awt.Dimension;
        import java.awt.event.ActionEvent;
        import java.awt.event.ActionListener;
    
        import javax.swing.JButton;
        import javax.swing.JComponent;
        import javax.swing.JFrame;
        import javax.swing.JPanel;
    
        public class Hello extends JPanel implements ActionListener {
    
            JButton button;
    
            public Hello() {
    
                super(new BorderLayout());
                button = new JButton("Say Hello");
                button.setPreferredSize(new Dimension(180, 80));
                add(button, BorderLayout.CENTER);
    
                button.addActionListener(this);  //  This is how you add the listener
            }
    
            /**
            * Invoked when an action occurs.
            */
            public void actionPerformed(ActionEvent e) {
                System.out.println("Hello world!");
            }
    
    
            private static void createAndShowGUI() {
    
                JFrame frame = new JFrame("Hello");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
                JComponent newContentPane = new Hello();
    
                newContentPane.setOpaque(true);
                frame.setContentPane(newContentPane);
                frame.pack();
                frame.setVisible(true);
            }
    
            public static void main(String[] args) {
                javax.swing.SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        createAndShowGUI();
                    }
                });
            }
        }
    

提交回复
热议问题