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 18 of 18

Thread: How to Add ActionListener to a JButton in Swing?

  1. #1
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Post How to Add ActionListener to a JButton in Swing?

    This code is an example of how to add ActionListener to a JButton.

    When the JButton is clicked, the desired action is performed. In this case it prints a message to the console.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
     
    public class ButtonAction {
     
        private static void createAndShowGUI()  {
     
            JFrame frame1 = new JFrame("JAVA");
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            JButton button = new JButton(" >> JavaProgrammingForums.com <<");
            //Add action listener to button
            button.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e)
                {
                    //Execute when button is pressed
                    System.out.println("You clicked the button");
                }
            });      
     
            frame1.getContentPane().add(button);
            frame1.pack();
            frame1.setVisible(true);
        }
     
     
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  2. The Following 3 Users Say Thank You to JavaPF For This Useful Post:

    aydea (January 23rd, 2011), heshamwhite (May 30th, 2011), Pusillus (June 17th, 2012)


  3. #2
    Junior Member
    Join Date
    Jul 2009
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Thank you for helping. I think this book is moving a bit too quick for me. My friend says he learned nothing about Gui until his second year. I have started reading a new book, and I will post another question soon. Thanks again.

    IDK12

  4. #3
    Junior Member
    Join Date
    Oct 2009
    Posts
    19
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    inside the post method u can call get method. if u r sending post request.
    if u r sending get request u can call post method inside the Get method
    try it once.

  5. #4
    Super Moderator Json's Avatar
    Join Date
    Jul 2009
    Location
    Warrington, United Kingdom
    Posts
    1,274
    My Mood
    Happy
    Thanks
    70
    Thanked 156 Times in 152 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Are you on about servlets chinni?

    // Json

  6. #5
    Junior Member
    Join Date
    May 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    please i really need you to help me with a material to read on Java programming.. I will really appreciate

  7. #6
    Junior Member
    Join Date
    Sep 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Quote Originally Posted by JavaPF View Post
    This code is an example of how to add ActionListener to a JButton.

    When the JButton is clicked, the desired action is performed. In this case it prints a message to the console.

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
     
    public class ButtonAction {
     
        private static void createAndShowGUI()  {
     
            JFrame frame1 = new JFrame("JAVA");
            frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
            JButton button = new JButton(" >> JavaProgrammingForums.com <<");
            //Add action listener to button
            button.addActionListener(new ActionListener() {
     
                public void actionPerformed(ActionEvent e)
                {
                    //Execute when button is pressed
                    System.out.println("You clicked the button");
                }
            });      
     
            frame1.getContentPane().add(button);
            frame1.pack();
            frame1.setVisible(true);
        }
     
     
        public static void main(String[] args) {
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
                }
            });
        }
    }
    Hi!

    What code do I use instead of " System.out.println("You clicked the button");"
    if I want the button to open a new class from my code? In this case I want the button to randomly
    select five cards from my deck of cards in the code.

    //Necessary imports
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
     
    public class SlumpaKort extends JPanel {
     
    	private static final long serialVersionUID = 1L;
     
    	//Knappvariabler
    	private static String buttonString = "Slumpa Kort";
    	private JButton btnRefresh;
     
    	/*
    	 * SlumpaKort-konstruktor
    	 */
    	public SlumpaKort() {
     
    		//Skapa en JPanel
    		super(new BorderLayout());
     
    		//Skapa knappen
    		btnRefresh = new JButton(buttonString);
    		btnRefresh.setActionCommand(buttonString);
    		btnRefresh.addActionListener(new Clicked());
     
    		//Skapa en panel som knappen kan ligga på
    		JPanel buttonPane = new JPanel();
    		buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS));
    		buttonPane.add(btnRefresh);
     
     
    		buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));
     
    		//Lägg till allt ovan till fönstret
    		add(buttonPane, BorderLayout.PAGE_END);
    	}
     
    	/*
    	 * Klick-Event för knappen
    	 */
    	class Clicked implements ActionListener {
     
     
    		class Kort {
    			private String[] farg ={"Hjärter", "Spader", "Ruter", "Klöver"};
    			private String[] valor ={"Ess", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Knäckt", "Dam", "Kung"};
    			//* Visar vilka färger samt valörer som finns representerade i kortleken *//
     
    			public int f, v;
     
    			public Kort(int farg, int valor) {
    				if (farg < 1 || farg > 4 || 
    						//* Fyra fäger *//
     
    						valor <1 || valor > 13) { 
    						//* 13 valörer *//
     
    		}
    				f = farg;
    				v = valor;
    			}
     
    			public int geFarg() {
    				return f;
    			}
     
    			public int geValor() {
    				return v;
    			}
     
    			public String toString() {
     
    				return farg[f - 1] + " " + valor[v - 1];
    		}
    		}
     
    		public class Kortlek {
    			public Kort[] bunt = new Kort[52];
    			public int antal = 0;
     
    			public int geAntal () {
    				return antal;
    		}
     
    			public void laggOverst(Kort k) {
    				bunt[antal] = k;
    				antal++;
    		}
     
    			public Kort geOversta() {
    				antal--;
    				return bunt[antal];
    		}
     
    			public void görKortlek() {
     
    				for (int f=1; f<=4; f++)
    					for (int v=1; v<=13; v++)
    						laggOverst(new Kort(f, v));
    		}
    			public void blanda() {
     
    				for (int i=0; i<antal; i++) {
    					int n = i + (int)(Math.random() * (antal - i));
    							Kort temp = bunt[n];
    							bunt[n] = bunt[i];
    							bunt[i] = temp;
     
    		}}
    		public void main( String args[]){
     
    			//* Blanda kortlek *//
    			Kortlek kortlek = new Kortlek();
    			kortlek.görKortlek();
    			kortlek.blanda();
     
    			//*Loopar kortlek.geOversta fem gånger för att sedan dela ut fem slumpade kort*//
    			for (int i=0; i<5; i++){
    				Kort k = kortlek.geOversta();
    				System.out.println(k.toString());
    			}
    		}
    		}
     
    		public void actionPerformed(ActionEvent e) {
     
    			//Vad som ska hända när man klickar på knappen
    			JOptionPane.showMessageDialog(null, "Detta fungerar!");  
     
    		}
    	}
     
    	/*
    	 * Startpunkten för programmet.
    	 * Här skapas fönstret.
    	 */
    	public static void main(String[] args) {
     
    		//Skapa formen
    		JFrame frame = new JFrame("Cards");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setResizable(false);
    		frame.setLocationRelativeTo(null);
     
    		//Skapa TestButton
    		JComponent contentPane = new SlumpaKort();
    		contentPane.setOpaque(true);
    		frame.setContentPane(contentPane);
     
    		//Visa fönstret
    		frame.pack();
    		frame.setVisible(true);
     
    	}
     
    }

  8. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,589
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    It will be better for you to open your own thread with your own topic, instead of adding to an existing thread.

    You should isolate the code for
    I want ... to randomly select five cards from my deck of cards
    into a separate small program and get that logic to work and then merge that code into the larger program.

  9. #8
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Hello _Alvin,

    Yes please create a new thread and we will answer you there
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  10. #9
    Junior Member
    Join Date
    Sep 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    hi people,

    i'm finishing one application very simple, and i realise that i need more feedback messages.
    This button send packages into a device until it answers, but my info label didn't work.


    JButton okButton = new JButton("START");
    okButton.setAlignmentY(0.5f);
    okButton.addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){

    statusLabel.setText("Status: Sending..."); <-- doesn't appear unless i put in the comment line handleOKConfig();

    System.out.println(statusLabel.getText()); <-- always appears.

    handleOKConfig(); <-- call the method that send the packages
    }
    });

    Inside the method handleOKConfig() i have another indication of when the application has finished sending the packet, success message --> statusLabel.setText("Status: Target device in bootload mode!"); and work always.

    I think the problem is with addActionListener or actionPerformed. Someone can help me?

    Thanks!

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,589
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    doesn't appear unless i put in the comment line handleOKConfig();
    Not sure that adding a comment line to your code changes how it executes.

    Your problem could be with changing Swing GUI values from the Swing Event Thread. Swing can't update the GUI while your code is using the thread. Try putting the setText() in a SwingUtilities thread using an invoke... method.

  12. #11
    Junior Member
    Join Date
    Sep 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Can you give me a smal example? I don't understand cleary...

  13. #12
    Junior Member
    Join Date
    Sep 2010
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Quote Originally Posted by Norm View Post
    Not sure that adding a comment line to your code changes how it executes.

    Your problem could be with changing Swing GUI values from the Swing Event Thread. Swing can't update the GUI while your code is using the thread. Try putting the setText() in a SwingUtilities thread using an invoke... method.


    When i comment the handleOkConfig() line, my label show what i want. But i need that execute this method too.

    can you give a small example...I don't understand cleray...

  14. #13
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    SW Missouri
    Posts
    20,589
    Thanks
    50
    Thanked 2,235 Times in 2,207 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Do a Search for SwingUtilities. There should be sample code that you can copy.

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

    Cool Re: How to Add ActionListener to a JButton. Java Swing

    What does frame.pack do?

    Also, what is all that with invoke later and stuff like that? Why not invoke now?



    Seriously though, what's that about?

    Also, this is unrelated, but when is jdk 7.0 coming out?

    (And do you have to go download it yourself and go to the website every time a new one comes out or can you get Eclipse or some other compiler to alert you and take you to the download site or even download it for you automatically without having to have you do anything?)

    I'm not familiar with Swing Utilities or threads. I've seen examples like that a few times before and I've always wondered what it meant and what the purpose of it was.

  16. #15
    Member
    Join Date
    Jul 2010
    Location
    Washington, USA
    Posts
    307
    Thanks
    16
    Thanked 43 Times in 39 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    If I'm not mistaken, frame.pack(); applies all of the changes to the content pane.

  17. #16
    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: How to Add ActionListener to a JButton. Java Swing

    API Javadoc for frame.pack (inherited from Window.pack):
    Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. If the window and/or its owner are not yet displayable, both are made displayable before calculating the preferred size. The Window will be validated after the preferredSize is calculated.

  18. #17
    Junior Member
    Join Date
    Jun 2012
    Posts
    8
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    Thanks a lot this posted helped me a lot and saved me a lot of my hair :-D

  19. #18
    Junior Member
    Join Date
    Apr 2013
    Location
    Pittsburgh, PA
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: How to Add ActionListener to a JButton. Java Swing

    I am not sure I find it useful to post a solution where a function call has a parameter that is itself a function definition:
    (I know this started from post #1 of this thread)

    For example
    ...
    public static void main(String[] args)
    {
    javax.swing.SwingUtilities.invokeLater(new Runnable()
    {
    public void run()
    {
    createAndShowGUI();
    }
    }
    );
    ...

    Twently levels of doing that and who can follow???

    I tried redoing this code w/o {ie separating definitions) I ended up a compiler error that I couldn't do this
    because all my functions were static. If I were to do the construction of the GUI elements in the body of the
    constructor - say ButtonAction(), I shouldn't have to worry.

    So how would I add an ActionListener() to a button while w/i the constructor???

    maddog
    Last edited by maddog; April 24th, 2013 at 05:17 PM. Reason: Readability.

Similar Threads

  1. Java program to Add a JMenu toolbar to a Java Swing application
    By JavaPF in forum Java Swing Tutorials
    Replies: 6
    Last Post: March 6th, 2012, 11:25 AM
  2. JAVA Image Icon and JButton resizing problem
    By antitru5t in forum AWT / Java Swing
    Replies: 1
    Last Post: March 13th, 2009, 04:39 AM

Tags for this Thread