Programming with Passion

Make the best out of everything.

Tuesday 21 November 2017

Example for Gui, Event handling and multi threading in JAVA

import java.awt.event.*;
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.Font;
import java.util.Date;

class calc extends JFrame implements ActionListener,Runnable
{
private JLabel n1,n2,r,c;
private JTextField f1,f2,f3;
private JButton a,s,m,d;
Thread th,dt;

public calc(){
super("CALCULATOR");
setLayout(null);
c = new JLabel("Caculator");
c.setFont(new Font("Comic Sans MS",Font.BOLD,24));

n1 = new JLabel("Number 1");
n2 = new JLabel("Number 2");
r = new JLabel("Result");
f1 = new JTextField(10);
f2 = new JTextField(10);
f3 = new JTextField(10);
a = new JButton("+");

s = new JButton("-");
m = new JButton("*");
d = new JButton("/");
a.setFont(new Font("Comic Sans MS",Font.BOLD,24));
s.setFont(new Font("Comic Sans MS",Font.BOLD,24));
m.setFont(new Font("Comic Sans MS",Font.BOLD,24));
d.setFont(new Font("Comic Sans MS",Font.BOLD,24));
c.setBounds(150,30,200,50);
add(c);
n1.setBounds(30,60,200,50);
add(n1);
f1.setBounds(100,75,200,25);
n2.setBounds(30,90,200,50);

f2.setBounds(100,105,200,25);
r.setBounds(30,120,200,50);
f3.setBounds(100,135,200,25);
a.setBounds(100,170,50,50);
s.setBounds(200,170,50,50);
m.setBounds(100,240,50,50);
d.setBounds(200,240,50,50);
add(f1);
add(n2);

add(r);

add(f2);
add(f3);
add(a);
add(s);
add(m);
add(d);
a.addActionListener(this);
s.addActionListener(this);
m.addActionListener(this);
d.addActionListener(this);

th=new Thread(this);
th.start();

dt=new Thread(this);
dt.start();
}
public void run()
{
if(Thread.currentThread()==th)
{
for(;;)
{
if(c.getText().equals("Calculator"))
{
c.setText("                ");
}
else
{
c.setText("Calculator");
}
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
if(Thread.currentThread()==dt)
{
for(;;)
{
Date d=new Date();
this.setTitle(d.toString());
try
{
Thread.sleep(1000);
}
catch(Exception e){}
}
}

}
public void actionPerformed(ActionEvent e)
{
int num = Integer.parseInt(f1.getText());
int num2 = Integer.parseInt(f2.getText());
int re=0;
if(e.getSource()==a)
{
re=num+num2;
f3.setText(" "+re);

}
if(e.getSource()==s)
{
re=num-num2;
f3.setText(" "+re);
}
if(e.getSource()==m)
{
re=num*num2;
f3.setText(" "+re);
}
if(e.getSource()==d)
{
re=num/num2;
f3.setText(" "+re);
}


}


public static void main(String args[]){
calc c = new calc();
c.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c.setSize(400,400);
c.setVisible(true); 
}

}

No comments:

Post a Comment