Tuesday, April 12, 2016

Simple GUI to count up/down button click

PROBLEM:  Make a counter button in java


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.*;

import javax.swing.*;

public class UpDownPanel implements ActionListener {
private JFrame frame;
private JButton button1;
private JButton button2;
private JLabel label;
private JPanel panel;
private JPanel panel1;
private int count =50;
public void GuiAnimation(){
frame = new JFrame();
button1 = new JButton("Up");
button2 = new JButton("Down");
panel = new JPanel();
panel1 = new JPanel();
panel.add(button1);
panel.add(button2);
panel.setBackground(Color.darkGray);
label = new JLabel("Click:"+count);
panel1.add(label);
panel1.setBackground(Color.white);
button1.addActionListener(this);
button2.addActionListener(this);
frame.getContentPane().add(panel,BorderLayout.SOUTH);
frame.getContentPane().add(panel1, BorderLayout.NORTH);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent event){
if(event.getSource()==button1){
label.setText("Click:"+ ++count);
}else{
label.setText("Click:"+ --count);
}
}

}


//Main class or a driver class

public class UpDown {
public static void main(String[]args){
UpDownPanel upDown = new UpDownPanel();
upDown.GuiAnimation();
}

}




Output:









No comments: