Question

i'm trying to learn more about actionListeners.

I try to print out the message "Test Action", if the button "save" is clicked. Anyway, i don't get it at all.

Here is my code, hope anyone can help me out. Thanks in advance.

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.*;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

public class applet extends JApplet implements ActionListener {

    private static final long serialVersionUID = -5561312464056465383L;
    private JTextField txtNameEingeben;
    private JTextField txtPwEingeben;

    public applet() {
        getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
        JPanel panel = new JPanel();
        panel.setBackground(Color.DARK_GRAY);
        getContentPane().add(panel);
        panel.setLayout(null);
        JLabel lblANewLabel = new JLabel("Name");
        lblANewLabel.setHorizontalAlignment(SwingConstants.LEFT);
        lblANewLabel.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
        lblANewLabel.setBounds(33, 57, 117, 37);
        lblANewLabel.setForeground(Color.WHITE);
        panel.add(lblANewLabel);
        //TEXTFELD NAME
        txtNameEingeben = new JTextField();
        txtNameEingeben.setText("");
        txtNameEingeben.setBounds(162, 64, 134, 28);
        panel.add(txtNameEingeben);
        txtNameEingeben.setColumns(10);
        //TEXTFELD PASSWORT
        txtPwEingeben = new JTextField();
        txtPwEingeben.setText("");
        txtPwEingeben.setBounds(162, 113, 134, 28);
        panel.add(txtPwEingeben);
        txtPwEingeben.setColumns(10);
        //LABEL ÜBERSCHRIFT
        JLabel lblNamePasswort = new JLabel("Name & Passwort in einem Array     speichern");
        lblNamePasswort.setForeground(Color.WHITE);
        lblNamePasswort.setHorizontalAlignment(SwingConstants.CENTER);
        lblNamePasswort.setBounds(0, 23, 450, 16);
        panel.add(lblNamePasswort);
        JButton btnSave = new JButton("save");
        btnSave.setBounds(308, 251, 117, 29);
        panel.add(btnSave);
        btnSave.addActionListener(new events());    
    }

    public void save(ActionEvent event) {
        System.out.println("Button gedrückt.");
    }

    public void actionPerformed(ActionEvent event) {
        if (event.getSource(btnSave)) {
            System.out.println("Test Action");
        }
    }

    public static void main(String[] args) {
        applet applet1 = new applet();
        applet1.setVisible(true);
    }
}
Was it helpful?

Solution

  1. don't to use reserved Java class and method names as the name of your project. public class applet extends... should be public class MyApplet extends....,

  2. use proper Java Naming Convention

  3. use JFrame instead of JApplet, create JFrame as local variable instead of extends JFrame, similair as for private JTextField txtNameEingeben;

  4. use LayoutManager instead of AbsoluteLayout (setBounds(...))

  5. from btnSave.addActionListener(new events()); the events() isn't declared

  6. you should use event.getSource() == btnSave instead of event.getSource(btnSave)

  7. read the Oracle tutorial about How to Write an Action Listener

OTHER TIPS

ActionEvent#getSource() delivers the component responsible for firing. In case of buttons, Swing puts the button itself as a source. This means, that you need to check if the button is the source. There are two possibilities to do it in your code:

  1. Make button to a field:

    public class applet extends JApplet implements ActionListener {
    
      /**
     * 
     */
      private static final long serialVersionUID = -5561312464056465383L;
      private JTextField txtNameEingeben;
      private JTextField txtPwEingeben;
    
      private JButton btnSave;
    
      /**
       * Create the applet.
       */
      public applet() {
    
        ...
    
        lblNamePasswort.setHorizontalAlignment(SwingConstants.CENTER);
        lblNamePasswort.setBounds(0, 23, 450, 16);
        panel.add(lblNamePasswort);
    
        btnSave = new JButton("save");
        btnSave.setBounds(308, 251, 117, 29);
        panel.add(btnSave);
        btnSave.addActionListener(this);
    
      }
    
      public void actionPerformed(ActionEvent event) {
        if (btnSave.equals(event.getSource())) {
          save();
        }
      }
    
      public void save() {
        System.out.println("Button gedrückt.");
      }
      ...
    

    }

  2. A nicer way to implement it, is not to let the whole applet to implement Action listener, but just use inline implementations.

          public class applet extends JApplet {
    
            private static final long serialVersionUID = -5561312464056465383L;
            private JTextField txtNameEingeben;
            private JTextField txtPwEingeben;
    
            /**
             * Create the applet.
             */
            public applet() {
              getContentPane().setLayout(new GridLayout(1, 0, 0, 0));
    
              // left out
              ...              
    
              JButton btnSave = new JButton("save");
              btnSave.setBounds(308, 251, 117, 29);
              panel.add(btnSave);
              btnSave.addActionListener(new ActionListener() {
    
                @Override
                public void actionPerformed(ActionEvent e) {
                  save();
                }
              });
    
            }
    
            public void save() {
              System.out.println("Button gedrückt.");
            }
    
            public static void main(String[] args) {
              applet applet1 = new applet();
              applet1.setVisible(true);
            }
          }
    

You could replace :

// (Where 'events' seems to come from nowhere)
btnSave.addActionListener(new events()); 

By :

btnSave.addActionListener(
    new ActionListener() {
        public void actionPerformed(ActionEvent event)
        {
            //if (event.getSource() == btnSave) { // Usefull only in case 2.
                System.out.println("Test Action");
            //}
        }
});     

Your listener can be:

  1. declared like above (anonymously), OR,
  2. created by instantiating a class of yours which implements ActionListener (look here).

For option 2. as your embedding class implements ActionListener, you could have passed it as the parameter :

btnSave.addActionListener(this);


Note: Also you should follow every single recommendation of mKorbel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top