Results 1 to 12 of 12
  1. #1
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default adding action listener

    I am getting this error:

    The method addActionListener(ActionListener) in the type AbstractButton is not applicable for the arguments (userGUI)

    here is my code:

    Java Code:
    userGUI() {
    
    		JFrame jfrm = new JFrame("A simple jframe swing program");
    
    		jfrm.setSize(275, 100);
    
    		jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		JLabel jLab = new JLabel("Press a button.");
    		
    		JButton jbtnFirst = new JButton("First");
    		JButton jbtnSecond = new JButton("Second");
    		
    		jbtnFirst.addActionListener(this);
    		jbtnSecond.addActionListener(this);
    
    		jfrm.getContentPane().add(jbtnFirst);
    		jfrm.getContentPane().add(jbtnSecond);
    		
    		jfrm.getContentPane().add(jLab);
    
    		jfrm.setVisible(true);
    
    	}
    thanks.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: adding action listener

    The error tells you exactly what's wrong. You're only allowed to add an ActionListener as the parameter of that method. Does the userGUI implement this interface? As an aside, one solution is to have userGUI (which should be spelled UserGUI or even UserGui) implement the interface and then implement the interface's method, actionPerformed, but I don't recommend this. In fact as a general rule you shouldn't have GUI classes implement Listener interfaces. Much better would be to use anonymous inner classes or private inner classes.

  3. #3
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    ok. so here is my code, but when i click on a button, it does nothing, and gives me a weird error message.

    Java Code:
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    
    public class UserGui implements ActionListener {
    
    	JLabel jLab;
    
    	userGUI() {
    
    		JFrame jfrm = new JFrame("A simple jframe swing program");
    
    		jfrm.getContentPane().setLayout(new FlowLayout());
    
    		jfrm.setSize(275, 100);
    
    		jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		JLabel jLab = new JLabel("Press a button.");
    
    		JButton jbtnFirst = new JButton("First");
    		JButton jbtnSecond = new JButton("Second");
    
    		jbtnFirst.addActionListener(this);
    		jbtnSecond.addActionListener(this);
    
    		jfrm.getContentPane().add(jbtnFirst);
    		jfrm.getContentPane().add(jbtnSecond);
    
    		jfrm.getContentPane().add(jLab);
    
    		jfrm.setVisible(true);
    
    	}
    
    	public void actionPerformed(ActionEvent ae) {
    		if (ae.getActionCommand().equals("First")) {
    			jLab.setText("first button was pressed");
    		} else {
    			jLab.setText("second button was pressed");
    		}
    	}
    
    	public static void main(String[] args) {
    
    		SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				new userGUI();
    			}
    		});
    
    	}
    }
    error:

    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at userGUI.actionPerformed(userGUI.java:45)
    	at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    	at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    	at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    	at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    	at java.awt.Component.processMouseEvent(Unknown Source)
    	at javax.swing.JComponent.processMouseEvent(Unknown Source)
    	at java.awt.Component.processEvent(Unknown Source)
    	at java.awt.Container.processEvent(Unknown Source)
    	at java.awt.Component.dispatchEventImpl(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    	at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    	at java.awt.Container.dispatchEventImpl(Unknown Source)
    	at java.awt.Window.dispatchEventImpl(Unknown Source)
    	at java.awt.Component.dispatchEvent(Unknown Source)
    	at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    	at java.awt.EventQueue.access$000(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.awt.EventQueue$3.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.awt.EventQueue$4.run(Unknown Source)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    	at java.awt.EventQueue.dispatchEvent(Unknown Source)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    	at java.awt.EventDispatchThread.run(Unknown Source)

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: adding action listener

    It's main method is not creating the correct object:

    Java Code:
        public static void main(String[] args) {
     
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    new userGUI(); // *************** !!!!!
                }
            });
     
        }
    Then when you fix that, check out the line that this throwing the exception, and inspect the variables on that line (which you should be doing before posting the error here). One is null and your code will tell you why. In other words, if you track back in your code, you'll see that you don't initialize an important variable. You should go through these steps automatically whenever you run into an NPE.
    Last edited by Fubarable; 01-22-2012 at 04:53 PM.

  5. #5
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    oh... jLab = new JLabel("Press a button."); instead of JLabel jLab = new JLabel("Press a button.");

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: adding action listener

    Quote Originally Posted by droidus View Post
    oh... jLab = new JLabel("Press a button."); instead of JLabel jLab = new JLabel("Press a button.");
    Yep. This is what's known as variable shadowing. You have declared a variable within the constructor that has the same name as one in the class, so the local variable "shadows" the class field. It's a nice lesson I think, since if you're like me, you'll surely see this error again.

  7. #7
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    lol, ok, thanks for the heads up! this stuff is hard to learn! lol i'm hesitant to go right to net beans... there's a ton to learn!

    by the way, how would i get the next line to write on for a text area? here is what i have so far... i was thinking of counting all the rows, then writing to the one after that.

    Java Code:
    textArea.insert(jft.getText(), end);
    Last edited by droidus; 01-22-2012 at 07:31 PM.

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: adding action listener

    Quote Originally Posted by droidus View Post
    lol, ok, thanks for the heads up! this stuff is hard to learn! lol i'm hesitant to go right to net beans... there's a ton to learn!
    You're welcome.

    by the way, how would i get the next line to write on for a text area? here is what i have so far... i was thinking of counting all the rows, then writing to the one after that.

    Java Code:
    textArea.insert(jft.getText(), end);
    What textArea? Do you mean a JTextArea? If so, have you read the API to see what methods you should use? You should never guess at stuff like this but instead use the references that are available.

  9. #9
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    not sure if this is right, but...

    textArea.append("\n" + jft.getText());

  10. #10
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    is there any way to turn this into a method, so i don't have to write one over and over again? i would like to use variables, instead of defined variables...

    Java Code:
    jbtnSubmit.addActionListener(new ActionListener() {
    				public void actionPerformed(ActionEvent ae) {
    					
    					if (uI.getText() != null) {
    						textArea.append("\nUSER INPUT: " + uI.getText().toUpperCase());
    					}
    					else {
    						 JOptionPane.showMessageDialog(null, "Invalid command!", "Invalid Values Detected", 1);
    					}
    				}
    			});

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: adding action listener

    Sure, just create an ActionListener variable initiated with an anonymous inner class:

    Java Code:
          ActionListener myActionListener = new ActionListener() {
             
             public void actionPerformed(ActionEvent e) {
                if (uI.getText() != null) {
                   textArea.append("\nUSER INPUT: " + uI.getText().toUpperCase());
                } else {
                   JOptionPane.showMessageDialog(null, "Invalid command!",
                         "Invalid Values Detected", 1);
                }
             }
          };
          jbtnSubmit.addActionListener(myActionListener);
          anotherJButton.addActionListener(myActionListener);
          // etc....

  12. #12
    droidus is offline Senior Member
    Join Date
    Feb 2011
    Posts
    244
    Rep Power
    4

    Default Re: adding action listener

    I am trying to insert an image into my gui. i found a thread on here about it, but can't get it to work. here is my code:



    Java Code:
    private JScrollPane getContent(BufferedImage image) {
    		JPanel panel = new JPanel(new GridLayout(1, 0));
    		panel.add(new JLabel(new ImageIcon(image)));
    		panel.add(new JLabel(new ImageIcon(getImage())));
    		return new JScrollPane(panel);
    	}
    
    	private BufferedImage getImage() {
    		String path = "awesome.jpg";
    
    		URL url = getClass().getResource(path);
    		BufferedImage image = null;
    
    		try {
    			image = ImageIO.read(url);
    		} catch (IOException e) {
    			System.out.println("Error occured : " + e.getMessage());
    
    		}
    		return image;
    
    	}
    
    	public static void main(String[] args) throws IOException {
    
    		String path = "awesome.jpg";
    		BufferedImage image = ImageIO.read(new File(path));
    		JFrame fr = new JFrame();
    		fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		fr.getContentPane().add(new insertImage().getContent(image));
    		fr.setSize(600, 600);
    		fr.setLocation(200, 200);
    		fr.setVisible(true);
    	}
    i have tried both a direct path, as well as this. the image is located in my src folder, with the rest of my .java files.

    thanks.

Similar Threads

  1. Replies: 2
    Last Post: 12-11-2011, 10:44 PM
  2. Problem in action listener
    By cool in forum AWT / Swing
    Replies: 4
    Last Post: 11-16-2010, 07:44 AM
  3. Simple Action/Listener Help GUI
    By aanders5 in forum New To Java
    Replies: 24
    Last Post: 10-18-2010, 06:43 PM
  4. Action Listener
    By greatmajestics in forum AWT / Swing
    Replies: 8
    Last Post: 03-25-2010, 05:39 PM
  5. Action Listener? how to use this?
    By jeffrey in forum New To Java
    Replies: 2
    Last Post: 10-12-2009, 08:51 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •