Chitika

Swing

The true sign of intelligence is not knowledge but imagination. Albert Einstein 

Introduction to Swing

A GUI is constructed from:

Containers: A GUI component that can contain other components
A top-level container is not contained in any other container (example: JFrame)
Components : Components are placed inside a Container
Defined in javax.swing package
Examples: windows, buttons, labels, text fields, menus, scroll bars, …

Swing equivalent of AWT components
JLabel, JButton, JPanel, JSlider
New Swing componentsJColorChooser, JInternalFrame, JOptionPane, JToolBar, JEditorPane
Other simple components
JCheckBox, JRadioButton, JTextField, JTextArea, JFileChooser
Panels are the canvas for your program .
in Swing, they are called javax.swing.JPanels
panels draw graphical shapes and GUI elements
we can add panels to a frame, and then add shapes and GUI elements to the panels

JFrame Example code:
import java.awt.*; 
 import javax.swing.*; 
 public class JFrameDemo { 
 public static void main(String[] args) { 
    JFrame f = new JFrame("JFrame Demo"); 
    f.setSize(400, 150); 
    f.add(new JButton("Button 1"));
    f.addWindowListener(new ExitListener()); 
    f.setVisible(true); 
   } 
} 
Swing Equivalents of AWT Components
JLabel  :- New features: HTML content images, borders
JButton :- New features: icons, alignment, mnemonics
JPanel  :- New feature: borders
JSlider :- New features: tick marks and labels
JLabel
Main new feature: HTML content
If text is "<html>...</html>", it gets rendered as HTML
HTML labels only work in JDK 1.2.2 or later, or in Swing 1.1.1 or later.
In JDK 1.2 the label string must begin with <html>, not <HTML>. It is case-insensitive in JDK 1.3 and 1.4.
JLabel fonts are ignored if HTML is used. If you use HTML, all font control must be performed by HTML.
You must use <P>, not <BR>, to force a line break.

Example of using html with JLabels
JLabel lbl = new JLabel("<html><b><i><font color ='blue'>Hello</font></i></b></html>");

Another example

String labelText = "<html><FONT COLOR=WHITE>WHITE</FONT> and " +
"<FONT COLOR=GRAY>GRAY</FONT> Text</html>";

JLabel coloredLabel = new JLabel(labelText, JLabel.CENTER);

JButtonMain new feature: icons
1.Create an ImageIcon by passing the ImageIcon constructor a String representing a GIF or JPG file (animated GIFs are supported!).
From an applet, call getImage(getCodeBase()…) normally, then pass resultant Image to ImageIcon.

2.Pass the ImageIcon to the JButton constructor.
Alternatively, call setIcon. In fact, there are 7 possible images (rollover images, images for when button is depressed, etc.)

Other features
HTML content as with JLabel
Alignment: location of image with respect to text
Mnemonics: keyboard accelerators that let you use Alt-someChar to trigger the button.

A full example that demonstrate JLabels,JButtons and Borders
import javax.swing.*;
import java.awt.event.*;

public class GUI{
public static void main(String[] arg){
   JFrame f = new JFrame();
   JPanel p = new JPanel();

   JLabel lbl = new JLabel("<html><b><i><font color='blue'>Hello</font></i></b></html>");
   p.add(lbl);
   ImageIcon icon = new ImageIcon("GPS.gif");

   JButton b = new JButton(icon);
   p.add(b);

   JButton bt = new JButton("GPS",icon);
   p.add(bt);

   JButton btl = new JButton("GPS",icon);
   btl.setHorizontalTextPosition(SwingConstants.LEFT);
   p.add(btl);

   p.setBorder(BorderFactory.createTitledBorder("Java"));

   f.add(p);
   f.setSize(200,300);
   f.setVisible(true);

   }
}

Another Example of JLabel

import java.awt.*;
import javax.swing.*;
public class LabelDemo
{
  
   public static void main (String[] args)
   {
      JFrame frame = new JFrame ("Label Demo");
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      ImageIcon icon = new ImageIcon ("devil.gif"); // You should have the image in your current folder
      JLabel label1, label2, label3;
      label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);
      label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);
      label2.setHorizontalTextPosition (SwingConstants.LEFT);
      label2.setVerticalTextPosition (SwingConstants.BOTTOM);
      label3 = new JLabel ("Devil Above", icon, SwingConstants.CENTER);
      label3.setHorizontalTextPosition (SwingConstants.CENTER);
      label3.setVerticalTextPosition (SwingConstants.BOTTOM);
      JPanel panel = new JPanel();
      panel.setBackground (Color.cyan);
      panel.setPreferredSize (new Dimension (200, 250));
      panel.add (label1);
      panel.add (label2);
      panel.add (label3);
      frame.getContentPane().add(panel);
      frame.pack();
      frame.setVisible(true);
   }
}

Example program for Nested Panels

import java.awt.*;
import javax.swing.*;
public class NestedPanels
{
//-----------------------------------------------------------------
// Presents two colored panels nested within a third.
//-----------------------------------------------------------------
public static void main (String[] args)
{
     JFrame frame = new JFrame ("Nested Panels");
     frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
// Set up first subpanel
     JPanel subPanel1 = new JPanel();
     subPanel1.setPreferredSize (new Dimension(150, 100));
     subPanel1.setBackground (Color.green);
     JLabel label1 = new JLabel ("One");
     subPanel1.add (label1);
// Set up second subpanel
     JPanel subPanel2 = new JPanel();
     subPanel2.setPreferredSize (new Dimension(150, 100));
     subPanel2.setBackground (Color.red);
     JLabel label2 = new JLabel ("Two");
     subPanel2.add (label2);
// Set up primary panel
     JPanel primary = new JPanel();
     primary.setBackground (Color.blue);
     primary.add (subPanel1);
     primary.add (subPanel2);
     frame.getContentPane().add(primary);
     frame.pack();
     frame.setVisible(true);
}
}


JSplitPane Demo

import javax.swing.*;
              import java.awt.*;

              public class SpiltpaneDemo{
              public static void main(String[] arg){

                     JFrame f = new JFrame("JSplit Pane");
                     JSplitPane p = new JSplitPane();
                     p.setOpaque(true);
                     p.setDividerLocation(150);
                     JPanel left = new JPanel();
                     left.setBackground(new Color(255,0,0));
                     JPanel right = new JPanel();
                     right.setBackground(new Color(0,255,0));
                     p.setRightComponent(right);
                     p.setLeftComponent(left);
                     f.add(p);
                     f.setSize(700,300);
                     f.setVisible(true);
                     }
              }

Output of the program


 Review Questions

  1. Write a java program to create the following user interface

  2. Write a java program to create the GUI in Fig 2, and the number appears in the label should be incremented with each button click. Add a tool tip text to the button.Hint: Use the following code to add the tool tip text
    1. ...
    2. btn.setOpaque(true);
    3. btn.setToolTipText("Click the button");
    4. ...
    Fig 2
  3. Create the following GUIs and add the appropriate Look And Feels  
  4. CDE/Motif
    Windows
    Meta
  5. Create the following GUI and button clicks will set the color of the right hand pane
  6. 
    Sample Coding
    
    import javax.swing.*;  
    import java.awt.event.*;
    import java.awt.*; 
    public class Main implements ActionListener {
    // application object fields    
     
        JLabel label;
        JButton butt1;
        JButton butt2;
        JButton butt3;
        JPanel left;
        JPanel right;
    public void actionPerformed(ActionEvent e)
    {
    // check which button and act accordingly
       if (e.getSource()==butt1)
          right.setBackground(new Color(255,0,0));
       if (e.getSource()==butt2)
          right.setBackground(new Color(0,0,255)); 
       if (e.getSource()==butt3)
          right.setBackground(new Color(0,255,0));
    }
    
    public static void main(String[] args) {
     
       JFrame f = new JFrame("I am a JFrame");
       f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
       f.setBounds(20,30,300,120);
       f.setLayout(null);
       Main app = new Main();
    //Create a split pane
       JSplitPane myPane = new JSplitPane();
       myPane.setOpaque(true);
       myPane.setDividerLocation(150);
       app.right = new JPanel();
       app.right.setBackground(new Color(255,0,0));
       app.left = new JPanel();
       app.left.setBackground(new Color(0,255,0));
       app.left.setLayout(null);
       myPane.setRightComponent(app.right);
       myPane.setLeftComponent(app.left);
    // make buttons
       app.butt1=new JButton("Red");
       app.butt2=new JButton("Blue");
       app.butt3=new JButton("Green");
    // add and size buttons
       app.left.add(app.butt1);
       app.butt1.setBounds(10,10, 100,20);
       app.left.add(app.butt2);
       app.butt2.setBounds(10,30, 100,20);
       app.left.add(app.butt3);
       app.butt3.setBounds(10,50, 100,20);
    // set up listener
       app.butt1.addActionListener(app);
       app.butt2.addActionListener(app);
       app.butt3.addActionListener(app);
       f.setContentPane(myPane);
       f.setVisible(true); 
     }
    }
    
  7. Create the following Used Car Program GUI
  8. Create the following GUI. When you type some text in the text field and press enter key, the text should appear in a label down to the text field.
  9. Sample code
        import javax.swing.*;  
        import java.awt.event.*; 
        import java.awt.*;
        
        public class TextFieldDemo implements ActionListener {
         
        	// application object fields    
        JLabel label;
        JTextField textField;
         public static void main(String[] args) {
                // start off..
            TextFieldDemo app=new TextFieldDemo();
            // make frame..
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("I am a JFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(20,30,300,120);
            frame.setLayout(null);
            // make a panel
            JPanel myPanel = new JPanel();
            // make a text field
            app.textField = new JTextField("Type here",20);
            myPanel.add(app.textField);
            // set up action listener
            app.textField.addActionListener(app);
            // make and add label
            app.label = new JLabel("Result");
            myPanel.add(app.label);
            frame.setContentPane(myPanel);
            frame.setVisible(true); 
               
            }  
           
        public void actionPerformed(ActionEvent e)
        {
            // this happens when Enter hit on the text field
            label.setText(textField.getText());
        }   
        
        }
  10. Create the following Scroll Pane GUI
      1. Sample Code
        import javax.swing.*;  
        import java.awt.event.*;
        import java.awt.*;
        
        public class ScrollPaneDemo implements ActionListener {
         
        public static void main(String[] args) {
                // start off..
           ScrollPaneDemo app=new ScrollPaneDemo();
            // make frame..
            JFrame.setDefaultLookAndFeelDecorated(true);
            JFrame frame = new JFrame("I am a JFrame");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setBounds(20,30,300,120);
            frame.setLayout(null);
            JSplitPane splitPane= new JSplitPane(); 
            JPanel left = new JPanel();
            JPanel right = new JPanel();    
            splitPane.setLeftComponent(left);
            JButton button = new JButton("Clear");
            left.add(button);
            button.addActionListener(app);
           // make a text field
            app.textArea = new JTextArea("Type here",5, 20);
           // make a panel
            JScrollPane scrollPane = new JScrollPane(app.textArea);
            splitPane.setRightComponent(scrollPane);
            frame.setContentPane(splitPane);
            frame.setVisible(true); 
            }
                
        public void actionPerformed(ActionEvent e)
            {
            // this happens when Enter hit on the text field
            textArea.selectAll();
            textArea.cut();
            }   
        
        }
        
  11. Create the following ScrollBar GUI
    Sample Code
    import javax.swing.*;  
      import java.awt.event.*;
    
      public class ScrollBarDemo implements AdjustmentListener {
      // application object fields   
                    JScrollBar sbar;  
      JLabel label; 
      public static void main(String[] args) {
              // make frame..
          JFrame f = new JFrame("JScrollBar");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.setBounds(20,30,200,300);
          f.getContentPane().setLayout(null);
    
          ScrollBarDemo app = new ScrollBarDemo();
    
          app.sbar = new JScrollBar   (java.awt.Adjustable.VERTICAL, 127,1,0,255);
          app.sbar.setBounds(20,20, 20, 200);
          app.sbar.addAdjustmentListener(app);
          f.getContentPane().add(app.sbar);
          app.label = new JLabel();
          app.label.setBounds(50,20,100,20);
          f.getContentPane().add(app.label);
    
          f.setVisible(true); 
        }   
        
      public void adjustmentValueChanged(AdjustmentEvent e)
      {
       label.setText("Value = "+e.getValue());
      }   
    
    }

Calculator Application


import javax.swing.*; 
import java.awt.event.*;
import java.awt.*;
import java.util.*;
public class Main implements ActionListener {
  
    private static void createAndShowGUI() {
    Main app = new Main();
    JFrame.setDefaultLookAndFeelDecorated(true);
    // make frame
    JFrame frame = new JFrame("Calc");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);
    frame.setBounds(50,50,190,170);
    // create top panel
    JPanel topPanel=new JPanel();
    topPanel.setBounds(0,0, 200,28);
    topPanel.setLayout(null);
    // add display to it
    app.display.setBounds(0,0, 200,28);
    app.display.setBackground(Color.black);
    app.display.setForeground(Color.green);
    app.display.setFont(new Font("Palatino",Font.PLAIN,14));
    topPanel.add(app.display);
    // show top panel
    frame.getContentPane().add(topPanel);
    // make lower panel
    JPanel lowerPanel=new JPanel();
    frame.getContentPane().add(lowerPanel);
    lowerPanel.setBounds(0,32, 180,100);
    lowerPanel.setLayout(new GridLayout(0,4,2,2));
    // add buttons to it
    app.add = new JButton("+");
    lowerPanel.add(app.add);
    app.sub = new JButton("-");
    lowerPanel.add(app.sub);
    app.mul = new JButton("X");
    lowerPanel.add(app.mul);
    app.div = new JButton("/");
    lowerPanel.add(app.div);
    for (int i=0; i<10; i++)
    {
        app.digits[i] = new JButton(""+i);
        app.digits[i].addActionListener(app);
        lowerPanel.add(app.digits[i]);    
    }
    app.point = new JButton(".");
    lowerPanel.add(app.point);
    app.point.addActionListener(app);
    app.equals = new JButton("=");
    lowerPanel.add(app.equals);
   
    frame.setVisible(true);  
    }
   
   
public void actionPerformed(ActionEvent e)
{
    for (int i = 0; i<10; i++)
    {
    if (e.getSource()==digits[i])
      current+=""+i;
    }
    if (e.getSource()==point)
        current+=".";
   
   
 
  display.setText(current);
}
    public static void main(String[] args) {
        // start off..
       try  {       
   UIManager.setLookAndFeel(  
   "javax.swing.plaf.metal.MetalLookAndFeel"   );  
      }
    catch (Exception e)
    {
    System.out.println("Cant get laf");
    }
   SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
   
// application object fields   
JButton add,sub, mul, div;
JButton point, equals;
JButton[] digits = new JButton[10];
String current = new String();
JTextField display = new JTextField();
}

Sample Notepad Application

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

public class MenuDemo{
           static JMenuItem open,exit;
public static void main(String[] arg){
       JFrame f = new JFrame("Menu Demo");
       JPanel layout = new JPanel();
       layout.setLayout(new BorderLayout());

       JTextArea ta = new JTextArea(50,50);
       layout.add(ta,BorderLayout.CENTER);
       JPanel p = new JPanel();
       p.setLayout(new FlowLayout(FlowLayout.LEFT));
       layout.add(p,BorderLayout.NORTH);
       JMenuBar bar = new JMenuBar();

       JSeparator js1 = new JSeparator();
       JMenu filemenu = new JMenu("File");
       JMenuItem itemnew = new JMenuItem("New");
       open = new JMenuItem("Open");
       open.addActionListener(new GUIEvents());
       JMenuItem save = new JMenuItem("Save");
       JMenuItem saveas = new JMenuItem("Save As");
       exit = new JMenuItem("Exit");
       exit.addActionListener(new GUIEvents());
       JMenuItem print = new JMenuItem("Print");

       bar.add(filemenu);
       filemenu.add(itemnew);
       filemenu.add(open);
       filemenu.add(save);
       filemenu.add(saveas);
       filemenu.add(js1);
       filemenu.add(print);
       filemenu.add(exit);

      JSeparator js2 = new JSeparator();
      JMenu editmenu = new JMenu("Edit");
      bar.add(editmenu);
      JMenuItem undo = new JMenuItem("Undo");
      JMenuItem cut = new JMenuItem("Cut");
      JMenuItem copy = new JMenuItem("Copy");
      JMenuItem paste = new JMenuItem("Paste");
      editmenu.add(undo);
      editmenu.add(js2);
      editmenu.add(cut);
      editmenu.add(copy);
      editmenu.add(paste);
      JMenu format = new JMenu("Format");
      bar.add(format);
      JMenuItem wr = new JMenuItem("Word Wrap");
      JMenuItem font = new JMenuItem("Font");
       format.add(wr);
       format.add(font);
      JMenu help = new JMenu("Help");
      bar.add(help);
      JMenuItem topic = new JMenuItem("Help Topics");
      JMenuItem about = new JMenuItem("About Us");
      help.add(topic);
      help.add(about);
      p.add(bar);
      f.add(layout);
      f.setSize(700,500);
      f.setVisible(true);
      }
}
class GUIEvents extends MenuDemo implements ActionListener{
 public void actionPerformed(ActionEvent e){
 if(e.getSource()==exit)
  System.exit(0);
 else if(e.getSource()==open){
  JFileChooser ch = new JFileChooser();
  ch.showOpenDialog(new JFrame());
 }

 }
}