Hello! So I’m doing a 30 day coding challenge where I solve a few questions every day and thought of posting them here on my blog so that you guys can join the challenge too!
Welcome to Coding challenge Day 28: Problem 1! Be sure to post your answers, queries etc in the comments!
Problem: Build a GUI in Java which counts the number of times that a button on the GUI is clicked
Author’s note: So this is entirely a new concept for me and I am having a lot a fun experimenting here and so today’s challenge is what I learnt on the first day. In the following video you may not understand everything but just go along with it. In the subsequent challenge we’ll get into much more details!! This challenge will give you the look and feel of GUI.
Solution:
Note that I just followed the video!
package Concepts;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GUI implements ActionListener{
private JFrame frame;
private JButton button;
private JPanel panel;
private JLabel label;
private int count=0;
public GUI(){
frame= new JFrame();
button= new JButton("Click me!");
panel= new JPanel();
label= new JLabel("Number of clicks: 0");
button.addActionListener(this);
panel.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
panel.setLayout(new GridLayout(0,1));
panel.add(button);
panel.add(label);
frame.add(panel, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("OUR GUI");
frame.pack();
frame.setVisible(true);
}
public static void main (String[] args){
new GUI();
}
@Override
public void actionPerformed(ActionEvent arg0) {
count++;
label.setText("Number of clicks: " + count);
}
}
Happy Learning!!