Java Swing GUI

Java GUI programming based on two packages:
  • Abstract windows kit (AWT)
  • Swing toolkit
import java.awt.*;                                                              
import java.awt.event.*;                                                        
import javax.swing.*;  //notice javax                                           
public class JavaGUI1 extends JFrame                                            
{                                                                               
  JPanel pane = new JPanel();                                                   
  JavaGUI1() // constructor method                                              
  {                                                                             
    super("My Java Frame"); setBounds(200,200,400,200);                         
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                             
    Container con = this.getContentPane(); // main frame                        
    con.add(pane); // add the panel in frame container                          
                                                                                
    //Add label                                                                 
    JLabel label = new JLabel("Welcome to Java Swing");                         
    label.setLocation(0, 0);                                                    
    label.setSize(100, 30);                                                     
    label.setHorizontalAlignment(0);                                            
    label.setForeground(Color.blue);                                            
    pane.add(label);                                                            
                                                                                
    setVisible(true); // display frame                                          
  }                                                                             
  public static void main(String args[]) {new JavaGUI1();}   
Compile and run Swing program:
$javac JavaGUI1.java
$java JavaGUI1
Getting below exception:
$ java JavaGUI1
Exception in thread "main" java.awt.HeadlessException
	at java.awt.GraphicsEnvironment.checkHeadless(GraphicsEnvironment.java:204)
	at java.awt.Window.(Window.java:536)
	at java.awt.Frame.(Frame.java:420)
	at javax.swing.JFrame.(JFrame.java:233)
	at JavaGUI1.(JavaGUI1.java:9)
	at JavaGUI1.main(JavaGUI1.java:17)
To resolve this java.awt.HeadlessException, install openjdk package.
$ sudo dnf install java-1.8.0-openjdk
Run again once installed openjdk package
$java JavaGUI1
Output:
JFrame Output

ActionListener

ActionListener interface is used to action to control like button press.

Panel with Button

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;  //notice javax
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JavaGUI1 extends JFrame implements ActionListener{
  JPanel panel = new JPanel();
  JButton btnIncrease, btnDecrease;
  JLabel label, lblValue;
  JavaGUI1() // constructor method
  {
    super("My Java Frame");
    //To align panel based on setLayout and setSize method of controls.
    panel.setLayout(null); 
    setBounds(200,300,400,300); 
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Container con = this.getContentPane(); // main frame
    //con.setLayout(null);
    con.add(panel); // add the panel in frame container

    //Add label
    label = new JLabel("Welcome to Java Swing");
    label.setLocation(0, 0);
    label.setSize(400, 40);
    label.setHorizontalAlignment(0);
    label.setForeground(Color.blue);
    panel.add(label);

    lblValue = new JLabel("Value: 0");                                
    lblValue.setLocation(10, 50);                                                    
    lblValue.setSize(100, 30);                                                     
    lblValue.setHorizontalAlignment(0);                                            
    lblValue.setForeground(Color.red);                                            
    panel.add(lblValue);   

    btnIncrease = new JButton("Increment");
    btnIncrease.setLocation(10, 100);
    btnIncrease.setSize(120, 30);
    btnIncrease.addActionListener(this);
    panel.add(btnIncrease);

    btnDecrease = new JButton("Decrement");                                     
    btnDecrease.setLocation(10, 150);                                            
    btnDecrease.setSize(120, 30);                                               
    btnDecrease.addActionListener(this);                                        
    panel.add(btnDecrease);   

    setVisible(true); // display frame
  }
  public void actionPerformed(ActionEvent e) {
   if(e.getSource() == btnIncrease)
   {  
      String[] value = lblValue.getText().split(" ");
      lblValue.setText("Value: "+Integer.toString(Integer.parseInt(value[1])+1));
    }
    else {
      String[] value = lblValue.getText().split(" ");                           
      lblValue.setText("Value: "+Integer.toString(Integer.parseInt(value[1])-1));
    }
  }
  public static void main(String args[]) {new JavaGUI1();}
}
Output:
JFrame Output
if panel.setLayout(null) is not added in above code, output looks as below
JFrame Output

Calculator using Java Swing

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class JavaGUI2 implements ActionListener {

    JPanel panel1, panel2, panel3;
    JTextField txtCalc;
    JLabel lblResult;
    JButton sumButton, minusButton, num1Button, num2Button, num3Button, num4Button;
    JButton equalButton, clearButton, num5Button, num6Button, num7Button, num8Button;
    JButton leftButton, rightButton, num9Button, num0Button, mulButton, divButton;

    public JPanel createMainPanel (){

        JPanel panel = new JPanel();
        panel.setLayout(null);

        panel1 = new JPanel();
        panel1.setLayout(null);
        panel1.setLocation(0, 0);
        panel1.setSize(400, 30);
        panel.add(panel1);

        txtCalc = new JTextField();
        txtCalc.setLocation(0, 0);
        txtCalc.setSize(400, 30);
        txtCalc.setForeground(Color.blue);
        //txtCalc.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        panel1.add(txtCalc);


        panel2 = new JPanel();
        panel2.setLayout(null);
        panel2.setLocation(0, 40);
        panel2.setSize(400, 200);
        panel.add(panel2);

        num1Button = new JButton("1");                                           
        num1Button.setLocation(10, 0);                                            
        num1Button.setSize(50, 30);                                              
        num1Button.addActionListener(this);                                      
        panel2.add(num1Button);   

        num2Button = new JButton("2");                                          
        num2Button.setLocation(70, 0);                                           
        num2Button.setSize(50, 30);                                              
        num2Button.addActionListener(this);                                     
        panel2.add(num2Button);

        num3Button = new JButton("3");                                          
        num3Button.setLocation(130, 0);                                           
        num3Button.setSize(50, 30);                                              
        num3Button.addActionListener(this);                                     
        panel2.add(num3Button);

        num4Button = new JButton("4");                                          
        num4Button.setLocation(190, 0);                                           
        num4Button.setSize(50, 30);                                              
        num4Button.addActionListener(this);                                     
        panel2.add(num4Button);

        sumButton = new JButton("+");
        sumButton.setLocation(250, 0);
        sumButton.setSize(50, 30);
        sumButton.addActionListener(this);
        panel2.add(sumButton);

        minusButton = new JButton("-");                                           
        minusButton.setLocation(310, 0);                                            
        minusButton.setSize(50, 30);                                             
        minusButton.addActionListener(this);                                      
        panel2.add(minusButton);  

        num5Button = new JButton("5");                                          
        num5Button.setLocation(10, 50);                                          
        num5Button.setSize(50, 30);                                             
        num5Button.addActionListener(this);                                     
        panel2.add(num5Button);                                                 
                                                                                
        num6Button = new JButton("6");                                          
        num6Button.setLocation(70, 50);                                          
        num6Button.setSize(50, 30);                                             
        num6Button.addActionListener(this);                                     
        panel2.add(num6Button);                                                 
                                                                                
        num7Button = new JButton("7");                                          
        num7Button.setLocation(130, 50);                                         
        num7Button.setSize(50, 30);                                             
        num7Button.addActionListener(this);                                     
        panel2.add(num7Button);                                                 
                                                                                
        num8Button = new JButton("8");                                          
        num8Button.setLocation(190, 50);                                         
        num8Button.setSize(50, 30);                                             
        num8Button.addActionListener(this);                                     
        panel2.add(num8Button);                                                 
                                                                                
        mulButton = new JButton("*");                                           
        mulButton.setLocation(250, 50);                                          
        mulButton.setSize(50, 30);                                              
        mulButton.addActionListener(this);                                      
        panel2.add(mulButton);                                                  
                                                                                
        divButton = new JButton("/");                                         
        divButton.setLocation(310, 50);                                        
        divButton.setSize(50, 30);                                            
        divButton.addActionListener(this);                                    
        panel2.add(divButton);                    

        num9Button = new JButton("9");                                          
        num9Button.setLocation(10, 100);                                          
        num9Button.setSize(50, 30);                                             
        num9Button.addActionListener(this);                                     
        panel2.add(num9Button);                                                 
                                                                                
        num0Button = new JButton("0");                                          
        num0Button.setLocation(70, 100);                                          
        num0Button.setSize(50, 30);                                             
        num0Button.addActionListener(this);                                     
        panel2.add(num0Button);                                                 
                                                                                
        leftButton = new JButton("(");                                          
        leftButton.setLocation(130, 100);                                         
        leftButton.setSize(50, 30);                                             
        leftButton.addActionListener(this);                                     
        panel2.add(leftButton);                                                 
                                                                                
        rightButton = new JButton(")");                                          
        rightButton.setLocation(190, 100);                                         
        rightButton.setSize(50, 30);                                             
        rightButton.addActionListener(this);                                     
        panel2.add(rightButton);                                                 
                                                                                
        equalButton = new JButton("=");                                           
        equalButton.setLocation(250, 100);                                          
        equalButton.setSize(50, 30);                                              
        equalButton.addActionListener(this);                                      
        panel2.add(equalButton);                                                  
                                                                                
        clearButton = new JButton("C");                                         
        clearButton.setLocation(310, 100);                                        
        clearButton.setSize(50, 30);                                            
        clearButton.addActionListener(this);                                    
        panel2.add(clearButton);                    
        panel.setOpaque(true);
        return panel;
    }
    // Override actionPerformed method of ActionListener interface to add action to controls.
    public void actionPerformed(ActionEvent e) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("js");
        if(e.getSource() == sumButton || e.getSource() == minusButton || e.getSource() == mulButton || e.getSource() == divButton)
        {
            if(txtCalc.getText().endsWith("+") || txtCalc.getText().endsWith("-") || txtCalc.getText().endsWith("*") || txtCalc.getText().endsWith("/")) {
             JOptionPane.showMessageDialog(null,"Invalid expression!","Message Dialog", JOptionPane.PLAIN_MESSAGE); 
            }
            else {
             try {
              txtCalc.setText(engine.eval(txtCalc.getText())+((JButton)e.getSource()).getText());
             } catch (ScriptException ex) {
               txtCalc.setText(txtCalc.getText()+((JButton)e.getSource()).getText());
             }
            }
        }
        else if(e.getSource() == equalButton)                                          
        {                                                                       
            if(txtCalc.getText().endsWith("+") || txtCalc.getText().endsWith("-") || txtCalc.getText().endsWith("*") || txtCalc.getText().endsWith("/")) {
             JOptionPane.showMessageDialog(null,"Invalid expression!","Message Dialog", JOptionPane.PLAIN_MESSAGE);
            }                                                                   
            else {                                                              
             try {                                                              
              txtCalc.setText(engine.eval(txtCalc.getText()).toString());              
             } catch (ScriptException ex) {                                     
             }                                                                  
            }                                                                   
        } 
        else if(e.getSource() == clearButton)                                          
        {                                                                       
              txtCalc.setText("");              
        }  
        else {
          txtCalc.setText(txtCalc.getText()+((JButton)e.getSource()).getText());
        }
    }

    private static void createGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame  form= new JFrame("Calculator");

        JavaGUI2 gui = new JavaGUI2();
        form.setContentPane(gui.createMainPanel());

        form.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        form.setSize(400, 300);
        form.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createGUI();
            }
        });
    }
}
Output:
JFrame Calculator Output

Evaluating Expression in Java

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
Object str = engine.eval("32+23");
engine.eval method throws ScriptException, need to handle or throws in calling method.
Java Examples

GCD and Rational Number Java Program

Java Queue Program using exception

Java Stack Program using exception

Addition of three integers java program

Biggest of three integers java program

Fibonacci numbers java program

Arithmetic Operations Menu java program

Second Smallest Element In Array Java Program

Transpose Of A Matrix Java Program

Java Program to Display triangle of stars (*)

Java Programming Prints Product Tables

Java Program to Display triangle of numbers

Java Program to Get Current Date

Java Program to Find Character Vowel or Consonent

Java Program to Compute HCF and LCM

Java Program to Sum the Command Line Integer Arguments

Java Programm to Multiply the Command Line Integer Arguments

Java Program to Find Multiplication of Command Line Floating Point Numeric Arguments

Java Program to Check String Contains or Not

Java Program to Get Grade Description using Switch

Java Program for CSV File Reader

Java Program to Find Character Frequency Count in String using for each

Java Program to Find Min from Integer Array by Passing Array to Method

Java Program Linear Search

Binary Search Java Program

Ternary Search Java Program

Java Program to Generate Range of Numbers

Java Program to Generate Range of Characters

Java Program to Compute Square Root Value

Java Program to Check Number is Positive or Negative

Java Program to Check Number is Odd or Even

Java Program to Compute Plot Area

Java Program to Convert Number of Days into Years

Java Program to Check a Year is Leap Year, Century Year or Not

Java Program to Check a Character is Digit, Letter or neither digit nor letter

Java Program to Check a Number is Palindrome or not

Java Program to Sum Two Matrix

Java Program to Compute Power

Java Program to Check Number is an Armstrong Number or not

Java Program for Temperature Unit Conversions

Java Program to Generate Random Numbers in Specified Range

Java Program to Compute Sum of Digits and Product of Digits

Java Program to Compute Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Program to Compute Harmonic Series

Java Program Generate Floyd's Triangle

Java Program to Reverse String

Java Program to Check Palindrome String or not

Java Program to Open Notepad

Java Program to Search String using RegEx Pattern

Java Program to Search Word in String

Java Program to Get System Environment Variables

Java Program to Get IP Address of Server Name

Java Program for Arrays Sorting and Reverse using sort method

Java Program for Bubble Sorting

Java Program for Selection Sorting

Java Program for Insertion Sorting

Java Program for Merge Sorting

Java Program for Quick Sorting

Java Program for Counting Sort

Java Program for Radix Sorting

Java Program for Sorting Array of Strings

Java Program for String Characters Sorting

Java Program to Sum First N Numbers

Java Program to Product First N Numbers

Java Program to get URL details

Java Program to get URL HTML Content

Java Program to get URL details

Java Program to get URL HTML Content

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^