Java Programming

Topic No. 12 : GUI Programming in Java

About AWT and Swing Packages
will be updated soon.
Basic Example of GUI
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
   public static void main(String[] args) {

    Pra1GUI t = new Pra1GUI();
        t.setSize(500, 500);
        t.setVisible(true);
      
   }
}           
Source Code for GUI
public class Pra1GUI extends JFrame implements ActionListener {
    
    JButton jb1;
    
    Pra1GUI()
    {
        jb1 = new JButton("OK");
        jb1.setBackground(Color.red);
        
        setLayout(new FlowLayout());
        add(jb1);
        jb1.addActionListener(this);
    }
    public void actionPerformed(ActionEvent e)
    {
        if(e.getSource() == jb1)
        {
            System.out.print("Hello World");
            JOptionPane.showMessageDialog(this, "Hello World","NUV",JOptionPane.INFORMATION_MESSAGE);
        }
    }
    
}

Different Layouts in Java
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
   public static void main(String[] args) {

        Demo d = new Demo();
        d.setSize(500,500);
        d.setVisible(true);
      
   }
}           
Source Code for Flowlayout
public class Demo extends JFrame {
    JPanel jp1,jp2,jp3,jp4,jp5;
    JButton jb1;
    public Demo()
    {
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jb1=new JButton("OK");
        jp2.add(jb1);
        jp1.setBackground(Color.yellow);
        jp2.setBackground(Color.red);
        jp3.setBackground(Color.blue);
        jp4.setBackground(Color.orange);
        jp5.setBackground(Color.cyan);
        setLayout(new FlowLayout());
        add(jp1);
        add(jp2);
        add(jp3);
        add(jp4);
        add(jp5);
        
    }
    
}
Source Code for Gridlayout
public class Demo extends JFrame {
    JPanel jp1,jp2,jp3,jp4,jp5;
    JButton jb1;
    public Demo()
    {
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jb1=new JButton("OK");
        jp2.add(jb1);
        jp1.setBackground(Color.yellow);
        jp2.setBackground(Color.red);
        jp3.setBackground(Color.blue);
        jp4.setBackground(Color.orange);
        jp5.setBackground(Color.cyan);
        setLayout(new GridLayout(3,2));
        add(jp1);
        add(jp2);
        add(jp3);
        add(jp4);
        add(jp5);
        
    }
    
}
Source Code for Borderlayout
public class Demo extends JFrame implements ActionListener {
    JPanel jp1,jp2,jp3,jp4,jp5;
    JButton jb1;
    public Demo()
    {
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jb1=new JButton("OK");
        jp2.add(jb1);
        jp1.setBackground(Color.yellow);
        jp2.setBackground(Color.red);
        jp3.setBackground(Color.blue);
        jp4.setBackground(Color.orange);
        jp5.setBackground(Color.cyan);
        setLayout(new BorderLayout());
        add(jp1,BorderLayout.NORTH);
        add(jp2,BorderLayout.SOUTH);
        add(jp3,BorderLayout.EAST);
        add(jp4,BorderLayout.WEST);
        add(jp5,BorderLayout.CENTER);
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        
    }
    
}
LogIn Form : Using Different Layouts
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
   public static void main(String[] args) {

        Demo t = new Demo();
        t.setSize(500, 500);
        t.setVisible(true);
        java.net.URL imageURL = Demo.class.getResource("myic.jpg");
        ImageIcon icon = new ImageIcon(imageURL);
        t.setIconImage(icon.getImage());
      
   }
}           
Source Code for GUI
public class Demo extends JFrame {
    JPanel jp1,jp2,jp3,jp4,jp5,jp6;
    JLabel jl1,jl2,jl3,jl4;
    JTextField jt1;
    JPasswordField jpf1;
    JButton jb1,jb2;
        Demo()
        {
        jp1 = new JPanel();
        jp2 = new JPanel();
        jp3 = new JPanel();
        jp4 = new JPanel();
        jp5 = new JPanel();
        jp6 = new JPanel();
        jl1= new JLabel("Student Data");
        jp1.add(jl1);
        jl2= new JLabel("Copyright - NUV");
        jp6.add(jl2);
        jl1.setForeground(Color.red);
        jl3= new JLabel("Enter Username");
        jl4= new JLabel("Enter Password");
        jt1 = new JTextField(10);
        jpf1 = new JPasswordField(10);
        jt1.setSize(50, 50);
        jb1= new JButton("LogIn");
        jb2= new JButton("Exit");
        jp2.setLayout(new GridLayout(3,1));
        jp3.add(jl3);
        jp3.add(jt1);
        jp4.add(jl4);
        jp4.add(jpf1);
        jp5.add(jb1);
        jp5.add(jb2);
        jp2.add(jp3);
        jp2.add(jp4);
        jp2.add(jp5);



        setLayout(new BorderLayout());
        add(jp1,BorderLayout.NORTH);
        add(jp2,BorderLayout.CENTER);
        add(jp6,BorderLayout.SOUTH);

        }
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource()==jb1)
            {
                String s1,s2;
                s1 = jt1.getText();
                s2 = jpf1.getText();
                System.out.print("\nUsername is "+s1);
                System.out.print("\nPassword is "+s2);
            }
            else if(e.getSource()==jb2)
            {
                System.exit(0);
            }
        }
}
Demo : JDialog,JFileChooser Open/Save, JWindow
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
   public static void main(String[] args) {

        Demo t = new Demo();
        t.setSize(500, 500);
        t.setVisible(true);
        java.net.URL imageURL = Demo.class.getResource("myic.jpg");
        ImageIcon icon = new ImageIcon(imageURL);
        t.setIconImage(icon.getImage());
      
   }
}           
Source Code for GUI
public class Demo extends JFrame implements ActionListener {
    JPanel jp1;
   
    JButton jb1,jb2,jb3;
        Demo()
        {
        jp1 = new JPanel();
        jb1= new JButton("Dialog Box Demo");
        jb2= new JButton("File Chooser Open");
        jb3= new JButton("Window Demo");
        setLayout(new FlowLayout());
        add(jb1);
        add(jb2);
        add(jb3);
        
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);

        }
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource()==jb1)
            {
               JDialog jd = new JDialog(this, "Demo Dialog");
               JLabel l = new JLabel("Sample Label");
               jd.setSize(200, 100);
               jd.add(l);
               jd.setVisible(true);
            }
            else if(e.getSource()==jb2)
            {
                JFileChooser fc=new JFileChooser();    
                int i=fc.showOpenDialog(this);
            }
            else if(e.getSource()==jb3)
            {
                JWindow jw = new JWindow();
                JLabel l = new JLabel("Sample Label");
                jw.add(l);
                jw.setSize(200, 200);
                jw.setVisible(true);
            }
        }
}

Demo : Set Look and Feel and changing the Icon of App
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
    public static void main(String[] args) {
            // TODO code application logic here
            UIManager.LookAndFeelInfo[] l1 = UIManager.getInstalledLookAndFeels();
            for(UIManager.LookAndFeelInfo l:l1)
            {
                System.out.print("\n "+l.getClassName());
            }
            /*javax.swing.plaf.metal.MetalLookAndFeel
            javax.swing.plaf.nimbus.NimbusLookAndFeel
            com.sun.java.swing.plaf.motif.MotifLookAndFeel
            com.sun.java.swing.plaf.windows.WindowsLookAndFeel
            com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel*/
            try
            {
                //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            }
            catch(Exception e)
            {
             System.out.print("Error");
            }
            Pra1GUI t = new Pra1GUI();
            t.setTitle(":: Apple Inc ::");
            t.setVisible(true);
            URL img1 = Pra1GUI.class.getResource("img1.jpg");
            ImageIcon ic = new ImageIcon(img1);
            t.setIconImage(ic.getImage());
            }
}           
Source Code for GUI
public class Pra1GUI extends JFrame implements ActionListener {
    JPanel jp1;
   
    JButton jb1,jb2,jb3;
        Pra1GUI()
        {
        jp1 = new JPanel();
        jb1= new JButton("Dialog Box Demo");
        jb2= new JButton("File Chooser Open");
        jb3= new JButton("Window Demo");
        setLayout(new FlowLayout());
        add(jb1);
        add(jb2);
        add(jb3);
        
        jb1.addActionListener(this);
        jb2.addActionListener(this);
        jb3.addActionListener(this);

        }
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource()==jb1)
            {
               JDialog jd = new JDialog(this, "Demo Dialog");
               JLabel l = new JLabel("Sample Label");
               jd.setSize(200, 100);
               jd.add(l);
               jd.setVisible(true);
            }
            else if(e.getSource()==jb2)
            {
                JFileChooser fc=new JFileChooser();    
                int i=fc.showOpenDialog(this);
            }
            else if(e.getSource()==jb3)
            {
                JWindow jw = new JWindow();
                JLabel l = new JLabel("Sample Label");
                jw.add(l);
                jw.setSize(200, 200);
                jw.setVisible(true);
            }
        }
}

Demo : More Controls and Event Handling
Source Code of main class
package javaapplication1;

public class JavaApplication1 {
   
    public static void main(String[] args) {
            // TODO code application logic here
            UIManager.LookAndFeelInfo[] l1 = UIManager.getInstalledLookAndFeels();
            for(UIManager.LookAndFeelInfo l:l1)
            {
                System.out.print("\n "+l.getClassName());
            }
            /*javax.swing.plaf.metal.MetalLookAndFeel
            javax.swing.plaf.nimbus.NimbusLookAndFeel
            com.sun.java.swing.plaf.motif.MotifLookAndFeel
            com.sun.java.swing.plaf.windows.WindowsLookAndFeel
            com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel*/
            try
            {
                //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
                UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
            }
            catch(Exception e)
            {
             System.out.print("Error");
            }
            Pra1GUI t = new Pra1GUI();
            t.setTitle(":: Apple Inc ::");
            t.setVisible(true);
            URL img1 = Pra1GUI.class.getResource("img1.jpg");
            ImageIcon ic = new ImageIcon(img1);
            t.setIconImage(ic.getImage());
            }
}           
Source Code for GUI
public class  Pra1GUI extends JFrame implements WindowListener,MouseListener,KeyListener {​​​
    JTextArea jt1;
    JCheckBox jc1,jc2,jc3;
    JRadioButton jr1,jr2;
    static final int FPS_MIN = 0;
    static final int FPS_MAX = 30;
    static final int FPS_INIT = 15; //initial frames per second

    Pra1GUI()
    {​​​
        jt1 = new JTextArea(5,10);
        jc1 = new JCheckBox("pizza");
        jc2 = new JCheckBox("Pasta");
        jr1 = new JRadioButton("Veg");
        jr2 = new JRadioButton("Non Veg");
        ButtonGroup group = new ButtonGroup();
        group.add(jr1);
        group.add(jr2);
        JProgressBar progressBar;
        progressBar = new JProgressBar(0, 100);
        progressBar.setValue(40);
        progressBar.setStringPainted(true);
        add(progressBar);
        JSlider framesPerSecond = new JSlider(JSlider.HORIZONTAL,
        FPS_MIN, FPS_MAX, FPS_INIT);

        //Turn on labels at major tick marks.
        framesPerSecond.setMajorTickSpacing(10);
        framesPerSecond.setMinorTickSpacing(1);
        framesPerSecond.setPaintTicks(true);
        framesPerSecond.setPaintLabels(true);
        add(framesPerSecond);
        add(jr1);
        add(jr2);
        add(jc1);
        add(jc2);
        add(jt1);
        setLayout(new FlowLayout());
        addWindowListener(this);
        addMouseListener(this);
        jt1.addKeyListener(this);
    }​​​
    @Override
    public void windowOpened(WindowEvent e)
    {​​​
    }​​​
    @Override
    public void windowClosed(WindowEvent e)
    {​​​
        dispose();
        System.exit(0);
    }​​​
    @Override
    public void windowClosing(WindowEvent e)
    {​​​
        dispose();
        System.exit(0);
    }​​​
    @Override
    public void windowIconified(WindowEvent e)
    {​​​
    }​​​
    @Override
    public void windowDeiconified(WindowEvent e)
    {​​​
    }​​​
    @Override
    public void windowActivated(WindowEvent e)
    {​​​
    }​​​
    @Override
    public void windowDeactivated(WindowEvent e)
    {​​​
    }​​​
    @Override
    public void mouseClicked(MouseEvent e)
    {​​​
    //System.out.print("Mouse is Clicked");
    }​​​
    @Override
    public void mouseEntered(MouseEvent e)
    {​​​
    //System.out.print("Mouse is Entered");
    }​​​
    @Override
    public void mouseExited(MouseEvent e)
    {​​​
    //System.out.print("Mouse is Exited");
    }​​​
    @Override
    public void mousePressed(MouseEvent e)
    {​​​
    //System.out.print("Mouse is Pressed");
    }​​​
    @Override
    public void mouseReleased(MouseEvent e)
    {​​​
    //System.out.print("Mouse is Released");
    }​​​
    @Override
    public void keyTyped(KeyEvent e)
    {​​​
    if(e.getSource() == jt1)
    {​​​
        char c= e.getKeyChar();
        int a = c;
            if(a>=48 && a<57)
            {​​​
            }​​​
            else
            {​​​
                JOptionPane.showMessageDialog(this,"Numeric Values are allowed","::NUV::",JOptionPane.ERROR_MESSAGE);
                jt1.setText("");
            }​​​
            
        }​​​
    }​​​
    @Override
    public void keyPressed(KeyEvent e)
    {​​​
    }​​​
    @Override
    public void keyReleased(KeyEvent e)
    {​​​
    }​​​
}​​​

Demo : File Viewer
Source Code of main class
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

public class FileManager 
{

   
    public static void main(String[] args) 
    {
        
            Demo t = new Demo();
            t.setTitle(":: W3TechBlog Community ::");
            t.setVisible(true);
            try
            {
                URL img1 = new URL("https://www.w3techblog.com/icon/favicon.png");
                ImageIcon ic = new ImageIcon(img1);
                t.setIconImage(ic.getImage());
                t.setSize(600,600);
            }
            catch(Exception e)
            {
                
            }
            
            
    }
    
}
Source Code for GUI
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

public class Demo extends JFrame implements ActionListener {
    
        JPanel jp1,jp2,jp3;
        JTextArea jt1;
        JButton jb1,jb2,jb3;
        File file;
        JLabel jl1;
        Demo()
        {
            jp1 = new JPanel();
            jp2 = new JPanel();
            jp3 = new JPanel();
            jt1= new JTextArea(30,50);
            JScrollPane scrollableTextArea = new JScrollPane(jt1);  
            jl1= new JLabel(":: Developed  By : w3techblog.com ::");
            scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);  
            scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);  
            jb1= new JButton("Open");
            jb2= new JButton("Save");
            jb3= new JButton("Exit");
            setLayout(new BorderLayout());
            jp1.add(jb1);
            jp1.add(jb2);
            jp1.add(jb3);
            jp3.add(jl1);
            jp2.add(scrollableTextArea);
            add(jp1,BorderLayout.NORTH);
            add(jp2,BorderLayout.CENTER);
            add(jp3,BorderLayout.SOUTH);
            jb1.addActionListener(this);
            jb2.addActionListener(this);
            jb3.addActionListener(this);

        }
        public void actionPerformed(ActionEvent e)
        {
            if(e.getSource()==jb1)
            {
                JFileChooser fc=new JFileChooser();    
                int i=fc.showOpenDialog(this);
                
                
                if (i == JFileChooser.APPROVE_OPTION) 
                {
                    
                    
                    try
                    {
                        file = fc.getSelectedFile();
                        System.out.print(file.toString());
                        StringBuffer sb = new StringBuffer();
                        FileInputStream fis = new FileInputStream(file);
                        while(5==5)
                        {
                            int n = fis.read();
                            if(n==-1)
                            {
                                break;
                            }
                            else
                            {
                                //System.out.print((char)n);
                                sb.append((char)n);
                                jt1.setText(sb.toString());
                            }
                        }    
                    }
                    catch(Exception e1)
                    {
                        System.out.print(e1.getMessage());
                    }
                  
                } 
                else 
                {
            
                }
                
                
            }
            else if(e.getSource()==jb2)
            {
                try
                    {
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] b = new byte[10000];
                        b = jt1.getText().getBytes();
                        fos.write(b);
                        
                    }
                    catch(Exception e1)
                    {
                        System.out.print(e1.getMessage());
                    }
                
                
                
            }
            else if(e.getSource()==jb3)
            {
               this.dispose();
               System.exit(0);
            }
           
        }
    
}