Showing posts with label java swing. Show all posts
Showing posts with label java swing. Show all posts

May 14, 2019

April 14, 2015

Automatically typing notepad in java


A Notepad that works automatically in java


/**
 * Funny notepad automatically wishing birthday
 */
package com.blogspot.javabelazy.funny;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author +Vipin Cp
 *
 */
public class HappyBirthdayMessage {

/**
* @param tokyo
*/
public static void main(String[] tokyo) {
// TODO Auto-generated method stub
HappyBirthdayMessage message = new HappyBirthdayMessage();
String yourMessage = "Happy Birthday Jerin V George";
Runtime runtime = Runtime.getRuntime();
try {
                       Thread.sleep(5000);
runtime.exec("notepad");
Thread.sleep(3000);
message.createMessage(yourMessage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

private void createMessage(String message) {
// TODO Auto-generated method stub
try {
Robot robot = new Robot();
int length = message.length();
for(int i=0;i<length;i++){
char letter = message.charAt(i);
String keyVal = Character.toString(letter);
String variableName;
if(keyVal.equals(" ")){
variableName ="VK_SPACE";
}else{
variableName = "VK_"+keyVal.toUpperCase();
}


Class clazz = KeyEvent.class;
   Field field = clazz.getField(variableName);
   int keyCode = field.getInt(null);
   robot.keyPress(KeyEvent.VK_SHIFT);
   robot.keyPress(keyCode);
   robot.delay(1000);
}

} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

Java tips and trick by +belazy

http://javabelazy.blogspot.in/

January 11, 2015

How to create Dynamic table in java swing

How to create Dynamic Jtable in java swing using DefaultTableModel


Description : The program helps you to create a table in java swing, a new row will be automatically inserted into jtable, when the focus reaches on the end of the last row


/** DyanmicJTable
*
* version 1.0
** java source code download
+vinu vp
*/

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

import java.awt.Font;
import java.awt.Rectangle;
import javax.swing.JTextField;
import java.awt.GridBagLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;

import java.awt.GridBagConstraints;

/**
*
*/
/**
* @author MH370
*
*/
public class DyanmicJTable extends JFrame {
private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JButton sendBtn = null;
private JTextField firmCodeTxt = null;
private JPanel jPanel = null;
private JScrollPane jScrollPane = null;
private JTable priceTbl = null;
private DefaultTableModel tableModel = null;
/**
* This is the default constructor
*/
public DyanmicJTable() {
    super();
    initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
    this.setSize(600, 600);
    this.setContentPane(getJContentPane());
    this.setTitle("Price Indent Sender");
}
/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
    if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(null);
            jContentPane.add(getJButton(), null);
            jContentPane.add(getJTextField(), null);
            jContentPane.add(getJPanel(), null);
        }
    return jContentPane;
    }
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (sendBtn == null) {
sendBtn = new JButton();
sendBtn.setBounds(new Rectangle(218, 50, 176, 23));
sendBtn.setText("send file");
sendBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {

 
System.out.println(" sending file ..."); // TODO Auto-generated Event stub actionPerformed()
}
});
}
return sendBtn;
}
/**
* This method initializes jTextField
*
* @return javax.swing.JTextField
*/
private JTextField getJTextField() {
    if (firmCodeTxt == null) {
        firmCodeTxt = new JTextField();
        firmCodeTxt.setBounds(new Rectangle(30, 49, 170, 26));
    }
    return firmCodeTxt;
}
/**
* This method initializes jPanel
*
* @return javax.swing.JPanel
*/
private JPanel getJPanel() {
    if (jPanel == null) {
        GridBagConstraints gridBagConstraints = new GridBagConstraints();
        gridBagConstraints.fill = GridBagConstraints.BOTH;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.gridx = 0;

        jPanel = new JPanel();
        jPanel.setLayout(new GridBagLayout());
        jPanel.setBounds(new Rectangle(22, 105, 524, 214));
        jPanel.add(getJScrollPane(), gridBagConstraints);
    }
return jPanel;
}
/**
* This method initializes jScrollPane
*
* @return javax.swing.JScrollPane
*/
private JScrollPane getJScrollPane() {
        if (jScrollPane == null) {
                jScrollPane = new JScrollPane();
                jScrollPane.setViewportView(getJTable());
            }
    return jScrollPane;
}
/**
* This method initializes jTable
*
* @return javax.swing.JTable
*/
    private JTable getJTable() {
        if (priceTbl == null) {
            tableModel = new DefaultTableModel();
            tableModel.addColumn("Item code");
            tableModel.addColumn(" M R P");
            tableModel.addColumn(" Price");
            tableModel.addColumn(" Autobatch ");
            // Initial row
            String [] data = {"","","",""};
            tableModel.addRow(data);
           
            priceTbl = new JTable(tableModel);
            Font font = new Font("Book Antiqua", Font.PLAIN, 20);
            priceTbl.setRowHeight(25);
            priceTbl.setFont(font);
            priceTbl.getModel().addTableModelListener(new TableModelListener() {
               
                @Override
                public void tableChanged(TableModelEvent e) {
                    // TODO Auto-generated method stub

                    if(e.getColumn()==3 && (tableModel.getRowCount()-1)==e.getLastRow()){
                       
                       
                        String [] newRow = {"","","",""};
                        tableModel.addRow(newRow);
                       
                    }
                   
                }
            });
           

        }
        return priceTbl;
    }
   
   
public static void main(String[] args) {
    DyanmicJTable ebola = new DyanmicJTable();
    ebola.setVisible(true);
    ebola.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

One Indian girl - By chetan bhagat Buy a copy now


Java swing dynamic table example

how to create dynamic table in java http://javabelazy.blogspot.in/

September 28, 2014

Develop a Regional language translator in java

Java source code to for english to malayalam language translator

     There are many online English to malayalam translator available in internet. If you are searching for a full java source code to convert english to malayalam then please dont go through this post, this only an idea how to start working on a english to malayalam language convertor. The code here is not a complete code. Copy the code paste it in your eclipse/Net bean ide and run it.

     You can download the English to malayalam convertor jar application from the link given below.
Please provide your feedback, you can comment for any post in this blog. Genuine comments will be appreciated !!! 

     Some guys sent me alternate code through face book and gmail (probably better code) after reading the post. thanks to those guys. and i have appended all those code with those posts. so share your knowledge !

Language Translator Image
Language Translator in java

Author : +belazy


/**
* Developing for office use
*/


import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.BorderFactory;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import javax.swing.border.Border;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
/**
* @author True caller java *
*/
public class Translator extends JFrame {

private static final long serialVersionUID = 1L;
private JPanel jContentPane = null;
private JTextArea typeArea = null;
private JTextArea viewArea = null;
private Translator thisClass = null;
private Mozhi mozhiObj = null;
/**
* This method initializes Typing area
*
* @return javax.swing.JButton
*/
private JTextArea getTypingArea() {
if (typeArea == null) {
typeArea = new JTextArea();
//typeArea.setBounds(new Rectangle(50, 50, 600, 600));
typeArea.setBounds(new Rectangle(30, 20, 200, 100));
Border border = BorderFactory.createLineBorder(Color.BLACK);
typeArea.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
typeArea.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
//System.out.println(" Vipin C P");

}

public void keyTyped(KeyEvent e) {
//System.out.println(" Developing language Translator ");
//String engWord = typeArea.getText();
//viewArea.setText(mozhiObj.getMalayalam(engWord));
viewArea.setText(convertToMalayalam(typeArea.getText()));
}
public void keyPressed(KeyEvent e) {
//System.out.println(" English to south indian language translation ");
}
});
}
return typeArea;
}
protected String convertToMalayalam(String engWord) {
String englishWord = engWord;
String malWord = englishWord.replaceAll("A", "¦");
malWord = malWord.replaceAll("bi", "Ìß");
malWord = malWord.replaceAll("the", "çÄ");
malWord = malWord.replaceAll("sh", "×í");
return malWord;
}

/**
* This method initializes Typing area
*
* @return javax.swing.JButton
*/
private JTextArea getViewArea() {
if (viewArea == null) {
viewArea = new JTextArea();
Font malFont = new Font("Kerala", Font.PLAIN, 15);
Border border = BorderFactory.createLineBorder(Color.GRAY);
viewArea.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(10, 10, 10, 10)));
//viewArea.setBounds(new Rectangle(700, 50, 600, 600));
viewArea.setBounds(new Rectangle(250, 20, 200, 100));
viewArea.setEditable(false);
viewArea.setFont(malFont);
}
return viewArea;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Translator thisClass = new Translator();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}

/**
* This is the default constructor
*/
public Translator() {
super();
initialize();
}

/**
* This method initializes this
*
* @return void
*/
private void initialize() {
//this.setSize(1340, 720);
this.setSize(500, 200);
this.setContentPane(getJContentPane());
this.setTitle("CFED : English To Malayalam Translator");
mozhiObj = new Mozhi();
}

/**
* This method initializes jContentPane
*
* @return javax.swing.JPanel
*/
private JPanel getJContentPane() {
if (jContentPane == null) {
jContentPane = new JPanel();
jContentPane.setLayout(null);
//jContentPane.add(getLoginButton(), null);
jContentPane.add(getTypingArea(), null);
jContentPane.add(getViewArea(), null);
}
return jContentPane;
}

}






function : convertToMalayalam() is that converts english words to malayalam, work on it. you can use a separate class to do the job.


You can download the malayalam font from this link
FileName : Javabelazy72902
Pasword : independenceday

Please try this code and feedback...

here is an online malayalam editor link


Thanks to +deepajayaprakash payyanakkal


http://javabelazy.blogspot.in/

March 16, 2014

Java Program that sent Email with attachment


Send an Email with attachment in java window application (gmail smtp : Simple Mail Transfer Protocol)


You can also sent reminder email

import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.swing.JOptionPane;

public class SendMailSSL {
    public static void main(String[] args) {
        String msg = " Mail sent successfully (java mail service application)";
        Properties props = new Properties();
        props.put("mail.smtp.host", "smtp.gmail.com");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.debug", "true");  // Debug the program
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.port", "465");

        Session session = Session.getDefaultInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("senderMailId@gmail.com","senderPassword");
                }
            });

        try {

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("cfedprice@gmail.com"));
            message.setRecipients(Message.RecipientType.TO,
                    InternetAddress.parse("receiverMailId@yahoo.in"));
            message.setSubject(" Details about Syrian Revolution (Civil War) ");
            // create the message part
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            //message body
            messageBodyPart.setText("Hi,  This application send email with attachment to Receiver mail id ");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(messageBodyPart);
            //attachment
            messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource("D:\\FaceBook\\SyrianRevolution.txt");
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName("SyrianRevolution.txt");
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            //message.setFileName("hackThroughEmail.java");

            Transport.send(message);

            //System.out.println("Email sent successfully using this java application");
        } catch (MessagingException e) {
            msg = "Error while sending";
            throw new RuntimeException(e);
        }
        JOptionPane.showMessageDialog(null, msg);
    }
}

This example in java shows how to mail using java mail service to sent a mail. User need to create a gmail account). Automatic mail sending application using google spreadsheet (google script)

Image for success mail sent
Java SMTP Mail Sent Application


if you are getting an error : authentication failed, or gmail blocked login attempt, then you should enable the access for less secure apps in your account

 Some devices and apps use insecure sign-in technology to access your data.
Choosing Disable prevents these less secure devices and apps from accessing your Google Account.
Choosing Enable increases your chances of unauthorized account access but allows you to continue using these less secure devices and apps. Learn more

Access for less secure apps should be enabled


You can download the working jar from here download link
filename : javabelazy10203.rar
password for rar file extraction is : 12345ABCDE


Output

Email Template




http://javabelazy.blogspot.in/

December 16, 2013

ActionListeners example in java

ActionListeners example in java


 import java.awt.*;
import java.awt.event.*;

class click extends Frame implements ActionListener
{
Button b,p;

click()
{
this.setLayout(null);
b= new Button("pink");
p= new Button("blue");
b.setBounds(100,299,70,20);
p.setBounds(200,299,70,20);
this.add(p);
this.add(b);
b.addActionListener(this);
p.addActionListener(this);
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==p)
setBackground(Color.pink);
if(ae.getSource()==b)
setBackground(Color.blue);
}

public static void main(String a[])
{
click c=new click();
c.setTitle("adding button");
c.setSize(500,500);
c.setVisible(true);
}

}


Decimal to Binary calculation in java


//import java.io.*;

class dectobin
{

public static void main(String arg[])
{

int b;

//int a=Integer.parseInt(10);
int a=10;


while(a<=0)
{

b=a%2;
a=a/2;
System.out.print(b);
}

System.out.println(" Binary to decimal convertor in java source code");

}
}


Creating A frame in java

import java.awt.*;
class demoframe extends Frame
{
public static void main(String arg[])
{
demoframe f=new demoframe();
f.setSize(300,300);
f.setVisible(true);
f.setTitle("Dallas cowboy xkeycode");

}
}

Ceaser Encryption in java


import java.awt.*;
import java.awt.event.*;
//import java.awt.text.*;
import java.lang.*;



public class encryp extends Frame implements ActionListener

{

Label l1,l2,l3;
TextField t;
TextField t2,k;
String s1;


Button b,e;

encryp()
{
this.setLayout(null);

l1=new Label("Input :");
l1.setBounds(350,50,50,20);
this.add(l1);
//l1.addActionListener(this);
l2=new Label("key :");
l2.setBounds(350,100,50,20);
this.add(l2);
l3=new Label("Output :");
l3.setBounds(350,350,50,20);
this.add(l3);




t=new TextField(4);
t.setBounds(400,50,100,20);
this.add(t);
t.addActionListener(this);

k=new TextField(4);
k.setBounds(400,100,100,20);
this.add(k);
k.addActionListener(this);



t2=new TextField(4);
t2.setBounds(400,350,100,20);
this.add(t2);
t2.addActionListener(this);

b=new Button("Ceaser");
b.setBounds(300,140,50,30);
this.add(b);
b.addActionListener(this);

e=new Button("exit");
e.setBounds(410,300,50,30);
this.add(e);
e.addActionListener(this);



}

public void work()
{
System.out.println(" work ");
}

public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==b)
{
s1=t.getText();
StringBuffer s=new StringBuffer(s1);
System.out.println(t.getText());

//s.reverse();
System.out.println(s);
t2.setText(s.reverse());
}

if(ae.getSource()==e)
{
System.exit(0);
}

}

public void textChanged(TextEvent te)
{
System.out.println(" java source code  ");
}

public static void main(String arg[])
{

encryp e=new encryp();
e.setTitle(" encryption ");
e.setSize(900,600);
e.setVisible(true);
}


Simple applications, copy paste and run it...



http://belazy.blog.com/

August 05, 2013

Billing (inventory) system for shops

Billing system for medium size shops




This system can help the company to avoid overstocking. When an organisation overstocks, money is wasted since procuring, storing, and accounting for unneeded items require time, space, and money which could have been used on more critical assets. Likewise, when under stocking occurs the organisation will more likely to only partly meet their mission or possibly not meet the mission at all. Also, a weak inventory control system is more prone to errors and fraud.
      Having advanced systems on sales and inventories makes the company more productive, efficient and convenient both to the company and its client. The system is meant to help people show to customers more relevant items, hoping to expedite   and increase the sales and most importantly to increase the profit of the company. With the aid of sales and inventory systems, management can easily make consistent, reliable, and timely decisions.
Our inventory software is designed for any business that desires a complete control over stock levels and inventory tracking. This inventory software can be used either as a simple inventory control system or a complete manufacturing solution.
The main modules are the following
·         Purchase Module
·         Sales Module
·         Inventory Module
·         Report Module
·         User Module (Employee, Customer and Vendor management)

There will be two types of user (on the basis privilege).

1.      Administrator :

2.      Employees :
billing system login page
log in screen







Please visit our site  proximoTech 

Offical fb page : Trade

Java Fx Login page example


June 07, 2013

Validating 2 digit number in java Swing using Regular expression

How to check whether a number is two digit number in java swing using regular expression validator

Here you can see how rollnumber is verified

package swing;
public class RollNumberValidatorImpl  extends InputVerifier{
public boolean verify(String input) {
         boolean isRollNumber = false;
         String rollNumber = input;
         if(rollNumber!=null && rollNumber.length()>0){
             isRollNumber = rollNumber.matches("\\d{1,2}")? true: false;
         }
         return isRollNumber;
    }
    public static void main(String[] args) {
        RollNumberValidatorImpl r = new RollNumberValidatorImpl();
        System.out.println(r.verify("01"));
    }
}


+Java

How to create a JTextfield in java that accepts only digits

The code verify for four digit number in java textfield First of all you need to create a class that extends inputverifier, then you have to register this class with your text field

class test{ public static void main(string arg){
JTextField motorolaText = new JTextField();
motorolaText.setInputVerifier(new FirmCodeValidatorImpl()); } }


The above code will shows you how to call the validation class, and the below one is validation class, i used regular expression here to validate the input

import javax.swing.InputVerifier;
import javax.swing.JComponent;
import javax.swing.JTextField;

public class FirmCodeValidatorImpl  extends InputVerifier{
   
    @Override
    public boolean verify(JComponent input) {
        boolean isFirmCode = false;
        String firmCode = null;
        JTextField textField = (JTextField) input;
        if(textField!=null){
            firmCode = textField.getText();
            isFirmCode = firmCode.matches("\\d{4}")? true: false;
        }
        return isFirmCode;
    }
   }

How to check whether a number is two digit in java



if you are satisfied with the code please provide your comments


http://belazy.blog.in/

March 13, 2012

Scientific calculator in java

Scientific Calculator source code developed in java swing

Description : A simple Java Swing Calculator, Example for setBounds in java, Example for actionListener interface. Here i tried to Implement a simple Java Calculator. copy and paste the code to a notepad. compile the program with javac and run using command prompt java calculator




Author +belazy

/* this is a program to make a

calculator

using java program */

/* For SNR Sons Lab exam ...
 * @author belazy
 */




import java.awt.*;
import java.awt.event.*;

public class

Calculator

extends Frame implements ActionListener

{
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,ex,p1,eq,min,div,mul,cl,back;
TextField t;
int n,i;
int n1,n2;
int ans;

Calculator()
{
this.setLayout(null);
b0=new Button(" 0 ");
b1=new Button(" 1 ");
b2=new Button(" 2 ");
b3=new Button(" 3 ");
b4=new Button(" 4 ");
b5=new Button(" 5 ");
b6=new Button(" 6 ");
b7=new Button(" 7 ");
b8=new Button(" 8 ");
b9=new Button(" 9 ");
ex=new Button("exit");
p1=new Button("+");
min=new Button("-");
mul=new Button("X");
div=new Button("/");

eq=new Button("=");
cl=new Button("AC");
back=new Button("clear");

t=new TextField(40);

b0.setBounds(130,190,30,30);
b1.setBounds(100,100,30,30);
b2.setBounds(130,100,30,30);
b3.setBounds(160,100,30,30);
b4.setBounds(100,130,30,30);
b5.setBounds(130,130,30,30);
b6.setBounds(160,130,30,30);
b7.setBounds(100,160,30,30);
b8.setBounds(130,160,30,30);
b9.setBounds(160,160,30,30);
ex.setBounds(100,190,30,30);
p1.setBounds(190,100,30,30);
min.setBounds(190,130,30,30);
mul.setBounds(190,160,30,30);
div.setBounds(190,190,30,30);
eq.setBounds(160,190,30,30);
cl.setBounds(220,100,30,30);
back.setBounds(220,130,30,30);

t.setBounds(100,60,150,30);



this.add(b0);
this.add(b1);
this.add(b2);
this.add(b3);
this.add(b4);
this.add(b5);
this.add(b6);
this.add(b7);
this.add(b8);
this.add(b9);

this.add(ex);
this.add(p1);
this.add(mul);
this.add(min);
this.add(div);
this.add(eq);
this.add(cl);
this.add(back);

this.add(t);

b0.addActionListener(this);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);

ex.addActionListener(this);
p1.addActionListener(this);
mul.addActionListener(this);
div.addActionListener(this);
min.addActionListener(this);
eq.addActionListener(this);
cl.addActionListener(this);
back.addActionListener(this);
}


public void actionPerformed(ActionEvent ae)

{

if(ae.getSource()==ex)
{
System.exit(0);
}

if(ae.getSource()==p1) // while pressing plus
{

n1=Integer.parseInt(t.getText());
i=1; // this expression is for equals
t.setText("0");

}

if(ae.getSource()==min) // while pressing minus
{

n1=Integer.parseInt(t.getText());
i=2;
t.setText("0");

}

if(ae.getSource()==mul) // while pressing multiplication
{

n1=Integer.parseInt(t.getText());
i=3;
t.setText("0");

}

if(ae.getSource()==div) // while pressing division
{

n1=Integer.parseInt(t.getText());
i=4;
t.setText("0");

}
if(ae.getSource()==cl) // while pressing all clear
{

//n1=Integer.parseInt(t.getText());
//i=4;
t.setText("0");

}

if (ae.getSource()==back) // for back space
{
//if (!(t.getText().equals("0") && t.getText().length() > 1)

t.setText(t.getText().substring(0,t.getText().length()-1));

}




if(ae.getSource()==b0)
{
if(t.getText().equals("0"))
t.setText("0");
else
t.setText(t.getText() +"0");
}

if(ae.getSource()==b1)
{
if(t.getText().equals("0"))
t.setText("1");
else
t.setText(t.getText() +"1");
}

if(ae.getSource()==b2)
{
if(t.getText().equals("0"))
t.setText("2");
else
t.setText(t.getText() +"2");
}


if(ae.getSource()==b3)
{
if(t.getText().equals("0"))
t.setText("3");
else
t.setText(t.getText() +"3");
}

if(ae.getSource()==b4)
{
if(t.getText().equals("0"))
t.setText("4");
else
t.setText(t.getText() +"4");
}

if(ae.getSource()==b5)
{
if(t.getText().equals("0"))
t.setText("5");
else
t.setText(t.getText() +"5");
}

if(ae.getSource()==b6)
{
if(t.getText().equals("0"))
t.setText("6");
else
t.setText(t.getText() +"6");
}

if(ae.getSource()==b7)
{
if(t.getText().equals("0"))
t.setText("7");
else
t.setText(t.getText() +"7");
}

if(ae.getSource()==b8)
{
if(t.getText().equals("0"))
t.setText("8");
else
t.setText(t.getText() +"8");
}

if(ae.getSource()==b9)
{
if(t.getText().equals("0"))
t.setText("9");
else
t.setText(t.getText() +"9");
}
System.out.println(t.getText());

if(ae.getSource()==eq) //while pressing equals
{
n2=Integer.parseInt(t.getText());




switch(i)
{
case 1:
{

ans=n1+n2;
t.setText(Integer.toString(ans));
n1=0;
n2=0;
}
break;

case 2:
{

ans=n1-n2;
t.setText(Integer.toString(ans));
n1=0;
n2=0;

}
break;

case 3:
{

ans=n1*n2;
t.setText(Integer.toString(ans));
n1=0;
n2=0;

}
break;

case 4:
{

ans=n1/n2;
t.setText(Integer.toString(ans));
n1=0;
n2=0;

}
break;

}

}



}



public static void main(String free[])
{

Calculator c= new Calculator();
c.setTitle("

simple java calculator source code

");
c.setSize(600,600);
c.setVisible(true);

}

}


Hi Friends,

           This is my first program in java. so please try it out and find the issues. Thanks to ravi, vishnu , madhu, bithesh and nithin for support

/* contact me at belazy1987atgmail.com */

Most selling calculator in amazon ( Price around 1000) The best one, Buy this , worth buying.
fx-991 Ex ( Casio - the best calculator makers )
Hurry !! Before stock out

Another Program send by my friend,

simple java calculator source code

import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//<applet code=Calculator height=300 width=200></applet>
public class Calculator extends JApplet {
public void init() {
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}

class CalculatorPanel extends JPanel implements ActionListener {
JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;

private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}

public CalculatorPanel() {
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));

n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);

n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);

n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);

dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}

}
}


The above is an example code for java swing scientific calculator, copy and paste it as calculator.java, compile the code and run it.

Please provide your feedback.

Java applet tutorial

  1. How to run java applet in web browser

Similar posts

  1. calendar using java swing
  2. compare two images in java
  3. Developing an swing IDE in java
  4. Developing an Billing system in java using swing
  5. Chatting application in java
  6. Algorithm to find missing number in a sequence with minimum complexity
< Thanking you....

February 09, 2012

How to clear table value in java

Clear JTable Values



JTable table = null;
defaultTableModel = new DefaultTableModel();
table = new JTable(defaultTableModel);


defaultTableModel.getDataVector().removeAllElements();
table.repaint();
table.revalidate();


Thanking you....

February 06, 2012

Round bordered TextField in java

How to a make a round border or round corner text field / text area in java swing


Frequently asked questions like how is it possible to make my javatexfield and textarea either round corner or round border. Here is a solution for that, so please go through the code and reply
/*
*@author Elizebath
*/
public class RoundJTextField extends JTextField {
private Shape shaping;
public RoundJTextField(int size) {
super(size);
setOpaque(false);
}
protected void paintComponent(Graphics g) {
g.setColor(getBackground());
g.fillRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
super.paintComponent(g);
}
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawRoundRect(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
public boolean contains(int x, int y) {
if (shaping == null || !shaping.getBounds().equals(getBounds())) {
shaping = new RoundRectangle2D.Float(0, 0, getWidth()-1, getHeight()-1, 15, 15);
}
return shaping.contains(x, y);
}
}

JTextField t = new RoundJTextField(20);


more

How to create maximize and minimize java swing frame

How to create a window in java that having system screen size/dimension



JFrame frame = new JFrame();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);


Or

Dimension screenDimension = getScreenDimension();
frame.setSize(screenDimension.width,screenDimension.height );

private Dimension getScreenDimension() {
Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension dimension = toolkit.getScreenSize(); return dimension; }

How to set screen dimension to application window.

Hi Friends,

This is a small blog.





Please provide your valuable feedbacks



Thanking you.... +Belazy L 

February 05, 2012

Java calculator source code

A simple calculator in java with source code

Description : In this project simple calculator in java, i used getSource method to know which button is clicked, i didnt assigned any value to the button





package calculator;
import javax.swing.*;
import java.awt.event.*;
/*
 * java calculator
 */
class ScientificCalculator implements ActionListener
{
JFrame calculatorFrame;
JTextField calculatorTxt;
JButton b1,b2,b3,b4,b5,b6,b7,b8,b9,b0,bdiv,bmul,bsub,badd,bdec,beq,bdel,bclr;
static double a=0,b=0,result=0;
static int operator=0;
ScientificCalculator()
{
calculatorFrame=new JFrame("Java Calculator");
calculatorTxt=new JTextField();
b1=new JButton("1");
b2=new JButton("2");
b3=new JButton("3");
b4=new JButton("4");
b5=new JButton("5");
b6=new JButton("6");
b7=new JButton("7");
b8=new JButton("8");
b9=new JButton("9");
b0=new JButton("0");
bdiv=new JButton("/");
bmul=new JButton("*");
bsub=new JButton("-");
badd=new JButton("+");
bdec=new JButton(".");
beq=new JButton("=");
bdel=new JButton("Del");
bclr=new JButton("Clear");

calculatorTxt.setBounds(30,40,280,30);
b7.setBounds(40,100,50,40);
b8.setBounds(110,100,50,40);
b9.setBounds(180,100,50,40);
bdiv.setBounds(250,100,50,40);

b4.setBounds(40,170,50,40);
b5.setBounds(110,170,50,40);
b6.setBounds(180,170,50,40);
bmul.setBounds(250,170,50,40);

b1.setBounds(40,240,50,40);
b2.setBounds(110,240,50,40);
b3.setBounds(180,240,50,40);
bsub.setBounds(250,240,50,40);

bdec.setBounds(40,310,50,40);
b0.setBounds(110,310,50,40);
beq.setBounds(180,310,50,40);
badd.setBounds(250,310,50,40);

bdel.setBounds(60,380,100,40);
bclr.setBounds(180,380,100,40);

calculatorFrame.add(calculatorTxt);
calculatorFrame.add(b7);
calculatorFrame.add(b8);
calculatorFrame.add(b9);
calculatorFrame.add(bdiv);
calculatorFrame.add(b4);
calculatorFrame.add(b5);
calculatorFrame.add(b6);
calculatorFrame.add(bmul);
calculatorFrame.add(b1);
calculatorFrame.add(b2);
calculatorFrame.add(b3);
calculatorFrame.add(bsub);
calculatorFrame.add(bdec);
calculatorFrame.add(b0);
calculatorFrame.add(beq);
calculatorFrame.add(badd);
calculatorFrame.add(bdel);
calculatorFrame.add(bclr);

calculatorFrame.setLayout(null);
calculatorFrame.setVisible(true);
calculatorFrame.setSize(350,500);
calculatorFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
calculatorFrame.setResizable(false);

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
b6.addActionListener(this);
b7.addActionListener(this);
b8.addActionListener(this);
b9.addActionListener(this);
b0.addActionListener(this);
badd.addActionListener(this);
bdiv.addActionListener(this);
bmul.addActionListener(this);
bsub.addActionListener(this);
bdec.addActionListener(this);
beq.addActionListener(this);
bdel.addActionListener(this);
bclr.addActionListener(this);
}

public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
calculatorTxt.setText(calculatorTxt.getText().concat("1"));

if(e.getSource()==b2)
calculatorTxt.setText(calculatorTxt.getText().concat("2"));

if(e.getSource()==b3)
calculatorTxt.setText(calculatorTxt.getText().concat("3"));

if(e.getSource()==b4)
calculatorTxt.setText(calculatorTxt.getText().concat("4"));

if(e.getSource()==b5)
calculatorTxt.setText(calculatorTxt.getText().concat("5"));

if(e.getSource()==b6)
calculatorTxt.setText(calculatorTxt.getText().concat("6"));

if(e.getSource()==b7)
calculatorTxt.setText(calculatorTxt.getText().concat("7"));

if(e.getSource()==b8)
calculatorTxt.setText(calculatorTxt.getText().concat("8"));

if(e.getSource()==b9)
calculatorTxt.setText(calculatorTxt.getText().concat("9"));

if(e.getSource()==b0)
calculatorTxt.setText(calculatorTxt.getText().concat("0"));

if(e.getSource()==bdec)
calculatorTxt.setText(calculatorTxt.getText().concat("."));

if(e.getSource()==badd)
{
a=Double.parseDouble(calculatorTxt.getText());
operator=1;
calculatorTxt.setText("");
}


if(e.getSource()==bsub)
{
a=Double.parseDouble(calculatorTxt.getText());
operator=2;
calculatorTxt.setText("");
}

if(e.getSource()==bmul)
{
a=Double.parseDouble(calculatorTxt.getText());
operator=3;
calculatorTxt.setText("");
}

if(e.getSource()==bdiv)
{
a=Double.parseDouble(calculatorTxt.getText());
operator=4;
calculatorTxt.setText("");
}

if(e.getSource()==beq)
{
b = calculatorTxt.getText().equals("") ? 0:Double.parseDouble(calculatorTxt.getText());
switch(operator)
{
case 0: result=b;
break;

case 1: result=a+b;
break;

case 2: result=a-b;
break;

case 3: result=a*b;
break;

case 4: result=a/b;
break;

default: result=0;
}

calculatorTxt.setText(""+result);
}

if(e.getSource()==bclr)
calculatorTxt.setText("");

if(e.getSource()==bdel)
{
String s=calculatorTxt.getText();
calculatorTxt.setText("");
for(int i=0;i<s.length()-1;i++)
calculatorTxt.setText(calculatorTxt.getText()+s.charAt(i));
}

}

public static void main(String...s)
{
new ScientificCalculator();
}
}



Java scientific calculator full source code

java source code available here


http://javabelazy.blogspot.in/

February 01, 2012

Network monitoring in java to get all computer names in the network


Java Network Monitoring : To get all intra networked computer list


//Java network program to list out all available computers in intranet

import java.io.*;

public class NetworkUsers
{
static String all;
public static void main(String[] args)
{try {
// Execute command

Process child = Runtime.getRuntime().exec("net view");
// Get the input stream and read from it
InputStream in = child.getInputStream();
int c;
while ((c = in.read()) != -1)
{
char e=(char)c;
System.out.println(e);
//process((char)c);
}
in.close();
} catch (IOException e) { } }

private static void process(char c) {
// TODO Auto-generated method stub
System.out.print(c);
//all =String.valueOf(c) +all;
// System.out.println(all);
}


}


 Please provide your valuable comments

January 31, 2012

right alignment in jtable cell


Example for right alignment of jtable cells in java swing



java.awt.Font font = new java.awt.Font("Serif", Font.BOLD, 12);
JTable table = new JTable();
searchResult_tbl.setAutoCreateRowSorter(true);
DefaultTableCellRenderer tableCellRenderer = new DefaultTableCellRenderer();
tableCellRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
tableCellRenderer.setForeground(Color.BLACK);
tableCellRenderer.setFont(font);
table.getColumn("total").setCellRenderer(tableCellRenderer);
table.setGridColor(theme.getColorTableGrid());



Mastering the jtable see the tutorial

Eid Mubrak to all visitors

facebook page :  https://www.facebook.com

January 30, 2012

Printing TextPane in java

Java window application to print java textpane



package com.blog.javacode.print;
import javax.swing.JTable;
import javax.swing.JTextPane;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.text.MessageFormat;
public class PrintTextPane {
static MessageFormat headerMessage = new MessageFormat("java project source code");
static MessageFormat footerMessage = new MessageFormat("best java blog");
public static void main(String[] javacode) throws Exception {
PrinterJob printerJob = PrinterJob.getPrinterJob();
if(printerJob.printDialog()) {
JEditorPane jEditorPane = new JEditorPane("text/html", "text");
jEditorPane.read(new BufferedReader(new InputStreamReader(new FileInputStream(new File("belazy.html")))), "");
jEditorPane.repaint();
printerJob.setPrintable(jEditorPane.getPrintable(headerMessage, footerMessage));
printerJob.print();
}}}


The above example prints a java textpane with header and footer. user can define the header and footer here. Please post your valuable comments , after trying this code

January 07, 2012

java swing calendar

How to create a swing calendar in java.


Are you looking for a calendar in java swing, then here is the solution. The calendar works on java swing jframe

The use of calendar in java window as well as web application is inevitable.


java calendar for window application
Java swing calendar for window applications



/**
* Filename :Calendarium.java
* Author : belazy.blog.com
* Date : Sep 29, 2007
* Project Name : 
* Description : Display a calendar in java swing.
*/
package com.proximotech.kims.utils;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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



/**
* @see
* @author
* @author Seahawks
* @version 1.0
*/
public class Calendarium {
int month = java.util.Calendar.getInstance().get(java.util.Calendar.MONTH);
int year = java.util.Calendar.getInstance().get(java.util.Calendar.YEAR);;
JLabel l = new JLabel("", JLabel.CENTER);
String day = "";
JDialog d;
JButton[] button = new JButton[49];

public Calendarium(JFrame parent) {
d = new JDialog();
d.setModal(true);
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
JPanel p1 = new JPanel(new GridLayout(7, 7));
p1.setPreferredSize(new Dimension(430, 120));

for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
d.dispose();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
p1.add(button[x]);
}
JPanel p2 = new JPanel(new GridLayout(1, 3));
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
p2.add(previous);
p2.add(l);
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
p2.add(next);
d.add(p1, BorderLayout.CENTER);
d.add(p2, BorderLayout.SOUTH);
d.pack();
d.setLocationRelativeTo(parent);
displayDate();
d.setVisible(true);
}

/**
* @param panel_ins : instance of a panel
*
*
Description : This constructor is call the calendar
*
Date : Nov 8, 2011
*
Coded by : belazy..
*/
public Calendarium(JPanel panel_ins) {
d = new JDialog();
d.setModal(true);
String[] header = { "Sun", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat" };
JPanel p1 = new JPanel(new GridLayout(7, 7));
p1.setPreferredSize(new Dimension(430, 120));

for (int x = 0; x < button.length; x++) {
final int selection = x;
button[x] = new JButton();
button[x].setFocusPainted(false);
button[x].setBackground(Color.white);
if (x > 6)
button[x].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
day = button[selection].getActionCommand();
d.dispose();
}
});
if (x < 7) {
button[x].setText(header[x]);
button[x].setForeground(Color.red);
}
p1.add(button[x]);
}
JPanel p2 = new JPanel(new GridLayout(1, 3));
JButton previous = new JButton("<< Previous");
previous.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month--;
displayDate();
}
});
p2.add(previous);
p2.add(l);
JButton next = new JButton("Next >>");
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
month++;
displayDate();
}
});
p2.add(next);
d.add(p1, BorderLayout.CENTER);
d.add(p2, BorderLayout.SOUTH);
d.pack();
d.setLocationRelativeTo( panel_ins);
displayDate();
d.setVisible(true);
}



public void displayDate() {
for (int x = 7; x < button.length; x++)
button[x].setText("");
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"MMMM yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, 1);
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK);
int daysInMonth = cal.getActualMaximum(java.util.Calendar.DAY_OF_MONTH);
for (int x = 6 + dayOfWeek, day = 1; day <= daysInMonth; x++, day++)
button[x].setText("" + day);
l.setText(sdf.format(cal.getTime()));
d.setTitle("CALENDAR");
}

public String setPickedDate() {
if (day.equals(""))
return day;
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"dd-MM-yyyy");
java.util.Calendar cal = java.util.Calendar.getInstance();
cal.set(year, month, Integer.parseInt(day));
return sdf.format(cal.getTime());
}
}



Facebook comments