How to Create Java Swing Application

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
      JLabel lb1,lb2;
      JTextField txt1,txt2,txt3;
      JButton btn1,btn2;
       MyFrame()
      {
        setLayout(null); 
        Font F=new Font("Times New Roman",Font.BOLD,20);
        lb1=new JLabel("First Number");
        lb1.setBounds(20,20,150,30);
        lb1.setFont(F);
        lb1.setForeground(Color.BLUE);
        add(lb1);
        txt1=new JTextField();
        txt1.setBounds(150,20,150,30);
        txt1.setFont(F);
        txt1.setForeground(Color.RED);
        add(txt1);

        lb2=new JLabel("Second Number");
        lb2.setFont(F);
        lb2.setBounds(20,100,150,30);
       lb2.setForeground(Color.BLUE);
        add(lb2);
        txt2=new JTextField(); 
        txt2.setBounds(150,100,150,30);
        txt2.setForeground(Color.RED);
        txt2.setFont(F);
        add(txt2);

           txt3=new JTextField();
          txt3.setBounds(370,100,150,30);
          txt3.setFont(F);
          txt3.setForeground(Color.RED);
           txt3.setEditable(false);
          add(txt3); 
         btn1=new JButton("+");
         btn1.setBounds(90,150,80,20);
         btn1.setFont(F);
           btn1.addActionListener(this);
         add(btn1);
           
         btn2=new JButton("-");  
         btn2.setBounds(210,150,80,20);
         btn2.setFont(F);
         btn2.addActionListener(this);
       add(btn2);
      } 
        public void actionPerformed(ActionEvent ae)        
        {
                        int a,b,c=0;
                       a=Integer.parseInt(txt1.getText());
                       b=Integer.parseInt(txt2.getText());
                  if(ae.getSource()==btn1)
                              c=a+b;
                  if(ae.getSource()==btn2)
                             c=a-b;
              txt3.setText(Integer.toString(c));
         } 
}
class TestSwing 
{
    public static void main(String args[])
   {
               MyFrame M=new MyFrame();
               M.setTitle("Addition Program");
               M.setSize(800,500);
               M.setVisible(true);    
              M.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
}

 

Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *