Pages

Java simple counter

Source below will show you, how to create simple counter in java.

*********************************************************************
COMPLETE SOURCE CODE FOR : JavaSimpleCounter.java
*********************************************************************


import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import java.awt.Graphics;
import java.awt.Font;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.Color;
import java.awt.Font;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JavaSimpleCounter extends JLabel implements ActionListener
{
JButton buttonReset=new JButton("RESET");
JButton buttonCount=new JButton("CLICK HERE");
int countValue=0;
JFrame frame;
Font fontForNumber=new Font("Tahoma",Font.BOLD,80);

public JavaSimpleCounter()
{
frame=new JFrame("JAVA SIMPLE COUNTER");
frame.setLayout(new BorderLayout());
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(1,2));
buttonCount.addActionListener(this);
buttonReset.addActionListener(this);
panel.add(buttonCount);
panel.add(buttonReset);
frame.add(this,BorderLayout.CENTER);
frame.add(panel,BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,200);
frame.setVisible(true);
}

public void paint(Graphics g)
{
g.setFont(fontForNumber);
g.setColor(Color.BLACK);
g.fillRect(0,0,getSize().width,getSize().height);
g.setColor(Color.WHITE);
g.drawString(Integer.toString(countValue),10,80);
}

public void actionPerformed(ActionEvent event)
{
if(event.getSource()==buttonCount)
{
countValue++;
frame.repaint();
}

else if(event.getSource()==buttonReset)
{
Graphics panelGraphics=getGraphics();
panelGraphics.setFont(fontForNumber);
panelGraphics.setColor(Color.BLACK);
panelGraphics.fillRect(0,0,getSize().width,getSize().height);
panelGraphics.setColor(Color.RED);
panelGraphics.drawString(Integer.toString(0),10,80);
countValue=0;
frame.repaint();
}
}

public static void main(String[]args)
{
JavaSimpleCounter jsc=new JavaSimpleCounter();
}
}


*********************************************************************
JUST COMPILE AND EXECUTE IT
*********************************************************************
Related Posts Plugin for WordPress, Blogger...