Java Programming 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 Programming 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 Programming Gets Current Date

Java Programming Finds Character Vowel or Consonent

Java Programming HCF and LCM Computation

Java Programming Sum of Command Line Integer Arguments

Java Programming Multiplication of Command Line Integer Arguments

Java Programming Multiplication of Command Line Floating Point Numeric Arguments

Java Programming String Contains or Not

Java Programming Gets Grade Description using Switch

Java Programming CSV File Reader

Java Programming Character Frequency Count in String using for each

Java Programming Finds Min from Integer Array by Passing Array to Method

Java Programming Linear Search

Java Programming Binary Search

Java Programming Ternary Search

Java Programming Generates Range of Numbers

Java Programming Generates Range of Characters

Java Programming Computes Square Root Value

Java Programming Checks Number is Positive or Negative

Java Programming Checks Number is Odd or Even

Java Programming Computes Plot Area

Java Programming Convert Number of Days into Years

Java Programming Checks a Year is Leap Year, Century Year or Not

Java Programming Checks a Character is Digit, Letter or neither digit nor letter

Java Programming Checks a Number is Palindrome or not

Java Programming Sum of Two Matrix

Java Programming Power Computation

Java Programming Checks Number is an Armstrong Number or not

Java Programming Temperature Unit Conversions

Java Programming Generates Random Numbers in Specified Range

Java Programming Computes Sum of Digits and Product of Digits

Java Programming Computes Reverse Number

Java Programming Computes Factorial Value

Java Programming Checks Prime Number or not

Java Programming Computes Harmonic Series

Java Programming Generates Floyd's Triangle

Java Programming Reverses String

Java Programming Checks Palindrome String or not

Java Programming Opens Notepad

Java Programming Searches String using RegEx Pattern

Java Programming Searches Word in String

Java Programming Gets System Environment Variables

Java Programming Gets IP Address of Server Name

Java Programming Arrays Sort and Reverse using sort method

Java Programming Bubble Sorting

Java Programming Selection Sorting

Java Programming Insertion Sorting

Java Programming Merge Sorting

Java Programming Quick Sorting

Java Programming Counting Sort

Java Programming Radix Sorting

Java Programming Sorting Array of Strings

Java Programming String Characters Sorting

Java Programming Sum of First N Numbers

Java Programming Product of First N Numbers

Privacy Policy  |  Copyright@2017 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Free online programming tutorials

Email Facebook Google LinkedIn Twitter
^