Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: New Java user ActionListener question

  1. #1
    Junior Member
    Join Date
    Jul 2010
    Posts
    4
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default New Java user ActionListener question

    Hello all,

    I'm a new Java user and I'm trying out the ActionListener feature but I am not sure what is the best way to implement it. Below is my code where I've been testing out different Java features.

    Based on my code below, what is the best way to add an ActionListener to the OK Button and the Close Button? Perhaps the OK Button has a MessageBox that says "OK Button Pressed" and the Close Button closes the application.


    Thanks for the help!
    VBGuy

    package test;
     
    import javax.swing.*;
    import java.awt.*;
     
     
     
    public class Main {
     
        public static void main(String[] args) {
            //Hello();
            //Calc();
     
            ShowFrame();
        }
     
        public static void Hello() {
        System.out.println("Hello World");
        }
     
        public static void Calc() {
            int a, b, c;
            a = 1;
            b = 1;
            c = a + b;
            System.out.println(c);
        }
     
        public static void ShowFrame() {
     
            JFrame MyWindow = new JFrame("Hello World");
            MyWindow.setSize(800, 600);
            MyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyWindow.setLayout(null);
     
            //Text Field
            JTextField bbox = new JTextField(16);
            bbox.setBounds(10, 10, 100, 25);
     
            //Add Buttons
            JButton CloseButton = new JButton("Close");
            CloseButton.setBounds(10, 100, 90, 40);
     
            JButton OkButton = new JButton("Ok");
            OkButton.setBounds(100, 100, 90, 40);
     
            //Add to Frame
            MyWindow.add(CloseButton);
            MyWindow.add(bbox);
            MyWindow.add(OkButton);
     
     
            //Set Visible
            MyWindow.setVisible(true);
            bbox.setVisible(true);
            CloseButton.setVisible(true);
            OkButton.setVisible(true);
     
     
            //Set Action Listener
            CloseButton.addActionListener(null);
     
     
        }
     
    }
    Last edited by helloworld922; July 7th, 2010 at 04:03 PM. Reason: Please use [highlight=Java] tags around your code


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,064
    Thanks
    52
    Thanked 2,282 Times in 2,253 Posts

    Default Re: New Java user ActionListener question

    what is the best way to add an ActionListener
    The only way I know is to use the addActionListener() method.

  3. The Following User Says Thank You to Norm For This Useful Post:

    VBGuy (July 7th, 2010)

  4. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,335
    Thanks
    181
    Thanked 830 Times in 773 Posts
    Blog Entries
    5

    Default Re: New Java user ActionListener question

    You must implement the ActionListener interface by creating a new class or have your main class implement it for you. See
    How to Write an Action Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

  5. The Following User Says Thank You to copeg For This Useful Post:

    VBGuy (July 7th, 2010)

  6. #4
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,896
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: New Java user ActionListener question

    Please surround your code snippets with [highlight=Java]CODE goes here[/highlight]. It makes reading the code much easier.

  7. The Following User Says Thank You to helloworld922 For This Useful Post:

    VBGuy (July 7th, 2010)

  8. #5
    Member
    Join Date
    Jun 2010
    Posts
    48
    Thanks
    12
    Thanked 2 Times in 2 Posts

    Default Re: New Java user ActionListener question

    Or you can simply create an anonymous class when adding the listener.
    Example:
    //Set Action Listener
            CloseButton.addActionListener(new ActionListener() {
                     public void actionPerformed(ActionEvent event) {
                           //actions perform when the CloseButton is clicked
                     }
            });

    The other way by creating inner class would look like this:
    public class Main {
    ...
         TheHandler handler = new TheHandler();
         CloseButton.addActionListener(handler);
    ...
         //////// private inner class ////////
         private class TheHandler implements ActionListener {
                 public void actionPerformed(ActionEvent event) {
                          //actions perform when the CloseButton is clicked
                 }
         }
    }
    Last edited by Asido; July 19th, 2010 at 12:19 PM.

  9. #6
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,684
    Thanks
    25
    Thanked 333 Times in 309 Posts

    Default Re: New Java user ActionListener question

    I think the inner class is the best method by my opinion. It means you can create 1 actionListener that takes account of all possible actions and whatnot. By doing the other way, you have to create a new actionListener that is specific to that object. Here is a little bit of helper code for my perferred method:

    public class ButtonListener implements ActionListener
    {
    	public void actionPerformed(ActionEvent e)
        	{
        		Object source = e.getSource();
        		if(source instanceof JButton)
        		{
        			if(source == fileChooserButton)
        			{...}
        			else if(source == runButton)
                    {...}
                 }
                 else if(source instanceOf JComboBox)
                 {
                     if(source == whatever)
                     {...}
                  }
          }
    }

    And to assign the actionListener, you do this:
    ActionListener listener = new ButtonListener();
    fileChooserButton.addActionListener(listener);
    runButton.addActionListener(listener);
    whatever.addActionListener(listener);

    As long as you include the instanceOf comparisons and the object comparisons in the ActionListener, the listener will run fast and accurately. You can do it without them, but including them means including less if/else statements.
    Last edited by aussiemcgr; July 19th, 2010 at 12:20 PM.

  10. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,064
    Thanks
    52
    Thanked 2,282 Times in 2,253 Posts

    Default Re: New Java user ActionListener question

    create a new actionListener that is specific to that object
    That can make for easier to maintain code that will have fewer bugs and cause fewer problems.

    Having it all in one method multiplies the chances of coding/logic problems.

  11. #8
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Lightbulb Re: New Java user ActionListener question

    Try this:

    package test;
     
    import javax.swing.*;
    import java.awt.*;
     
     
     
    public class Main {
     
        public static void main(String[] args) {
            //Hello();
            //Calc();
     
            ShowFrame();
        }
     
        public static void Hello() {
        System.out.println("Hello World");
        }
     
        public static void Calc() {
            int a, b, c;
            a = 1;
            b = 1;
            c = a + b;
            System.out.println(c);
        }
     
        public static void ShowFrame() {
     
            JFrame MyWindow = new JFrame("Hello World");
            MyWindow.setSize(800, 600); // kinda big isn't it?  
            MyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            MyWindow.setLayout(null);
     
            //Text Field
            JTextField bbox = new JTextField(16);
            bbox.setBounds(10, 10, 100, 25);
     
            //Add Buttons
            JButton CloseButton = new JButton("Close");
            CloseButton.setBounds(10, 100, 90, 40);
     
            JButton OkButton = new JButton("Ok");
            OkButton.setBounds(100, 100, 90, 40);
     
            //Add to Frame
            MyWindow.add(CloseButton);
            MyWindow.add(bbox);
            MyWindow.add(OkButton);
     
     
            //Set Visible
            MyWindow.setVisible(true);
            bbox.setVisible(true);
            CloseButton.setVisible(true);
            OkButton.setVisible(true);
     
     
            //Set Action Listener
            CloseButton.addActionListener(this);
            OkButton.addActionListener(this);
     
        }
     
    public void actionPerformed (ActionEvent e)
    {
     if (e.getActionCommand().equals("Close")
    {
     System.exit(0);  // I'm assuming that's what you want by close
    }
     
    else if (e.getActionCommand().equals("Ok")
    {
     // code for whatever ok button is supposed to do
    }
     
     
    }
    }
    [/QUOTE]

Similar Threads

  1. How to Add ActionListener to a JButton in Swing?
    By JavaPF in forum Java Swing Tutorials
    Replies: 17
    Last Post: April 24th, 2013, 05:14 PM
  2. ActionListener help
    By QBird in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 1st, 2011, 11:25 AM
  3. ActionListener Help?
    By Drag01 in forum AWT / Java Swing
    Replies: 1
    Last Post: March 30th, 2010, 08:21 PM
  4. Replies: 2
    Last Post: November 19th, 2009, 10:55 PM
  5. Question about ActionListener
    By TimW in forum AWT / Java Swing
    Replies: 6
    Last Post: November 4th, 2009, 10:00 AM