JButton with ActionListener (Count!!!)

How is it going everybody? Pheww… Its been quite too long since my last article Ha! Now I’m back in shape with another new article. Today’s article is about a Button, well I’m feeling a little bit itchy about Button because I hasn’t made an interactive button (ActionListener). So today’s all about adding an ActionListener to a Button.

Okay so if you doesn’t know how to create a Button in Java, check out This article on how to create Button in Java : Button 

This is the code of a JButton :

 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {
    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);
      
    }  
}

First here is the code that implements ActionListener :

button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;

       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}

That’s it, now you just need to implement it to your original Button code :


 import javax.*;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;

public class Button {

    public static void main(String args[]){
        JFrame jframe = new JFrame(“Button”);
        jframe.setSize(300, 300);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(jframe.EXIT_ON_CLOSE);
      
        JPanel panel = new JPanel();
        jframe.add(panel);
        JButton button = new JButton(“Hello World”);
        button.setVisible(true);
        button.setSize(100, 100);
        panel.add(button);

        button.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent e) { 
      
      for(int i = 0; i < 20; i++){
       int s = 5;
       while(s < 20) {
         s++;
         System.out.println(s);
           }    
       }     
    }
}
      
    }  
}


That is a button that will count (increments (++) ) the number 5 by 1 and would go on while the number is still smaller (<) than 20.



1 thought on “JButton with ActionListener (Count!!!)”

Leave a Reply

Your email address will not be published. Required fields are marked *