Setting button actions programatically in Java, Python, JavaScript, SWIFT and Kotlin

By | January 9, 2024

Button action calls for an action when user tap on a button. This may be for making a service call, for doing some calculation or simply just to dismiss a view. Here are the different ways of setting button action in different languages.

Java

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Button Example");
        JButton button = new JButton("Click Me");

        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("Button Clicked!");
            }
        });

        frame.getContentPane().add(button);
        frame.setSize(300, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

Python (TKinter)

import tkinter as tk

def button_click():
    print("Button Clicked!")

root = tk.Tk()
button = tk.Button(root, text="Click Me", command=button_click)
button.pack()

root.mainloop()

JavaScript:

<html>
<body>

<button id="myButton">Click Me</button>

<script>
document.getElementById("myButton").addEventListener("click", function() {
    console.log("Button Clicked!");
});
</script>

</body>
</html>

Swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let button = UIButton(type: .system)
        button.setTitle("Click Me", for: .normal)
        button.addTarget(self, action: #selector(buttonClicked), for: .touchUpInside)

        view.addSubview(button)
        button.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            button.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            button.centerYAnchor.constraint(equalTo: view.centerYAnchor)
        ])
    }

    @objc func buttonClicked() {
        print("Button Clicked!")
    }
}

Kotlin

import android.os.Bundle
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val button = Button(this)
        button.text = "Click Me"
        button.setOnClickListener { buttonClicked() }

        setContentView(button)
    }

    fun buttonClicked() {
        println("Button Clicked!")
    }
}

These examples demonstrate how to set up button actions in different programming languages and frameworks. The actions vary slightly depending on the platform, but the basic idea is to associate a callback or listener with the button that gets triggered when the button is clicked. Adjust the code based on the specific UI framework or library you are using.

Leave a Reply

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