0% found this document useful (0 votes)
95 views55 pages

AJP With Java UNIT - 2 - 2: Raghavan P

The document provides examples of using various Java Swing components like JTextField, JButton, JCheckBox, JRadioButton, JTabbedPane, JViewport and JScrollBar. It includes code snippets to create and add these components to a JFrame window with appropriate properties and layouts. It also shows how to add listeners to components like ActionListener and AdjustmentListener to handle user interactions.

Uploaded by

Pavithra B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views55 pages

AJP With Java UNIT - 2 - 2: Raghavan P

The document provides examples of using various Java Swing components like JTextField, JButton, JCheckBox, JRadioButton, JTabbedPane, JViewport and JScrollBar. It includes code snippets to create and add these components to a JFrame window with appropriate properties and layouts. It also shows how to add listeners to components like ActionListener and AdjustmentListener to handle user interactions.

Uploaded by

Pavithra B
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 55

AJP with Java

UNIT – 2 - 2
Raghavan P
import javax.swing.*;  
class TextFieldExample  
{  
public static void main(String args[])  
    {  
    JFrame f= new JFrame("TextField Example");  
    JTextField t1,t2;  
    t1=new JTextField("Welcome to MCC");  
    t1.setBounds(50,100, 200,30);  
    t2=new JTextField(“MCC AWT Tutorial");  
    t2.setBounds(50,150, 200,30);  
    f.add(t1); f.add(t2);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
    }  
    }  
Java JTextField Example with ActionListener
import javax.swing.*;  
import java.awt.event.*;  
public class TextFieldExample implements ActionListener{  
    JTextField tf1,tf2,tf3;  
    JButton b1,b2;  
    TextFieldExample(){  
        JFrame f= new JFrame();  
        tf1=new JTextField();  
        tf1.setBounds(50,50,150,20);  
        tf2=new JTextField();  
        tf2.setBounds(50,100,150,20);  
        tf3=new JTextField();  
        tf3.setBounds(50,150,150,20);  
        tf3.setEditable(false);   
        b1=new JButton("+");  
        b1.setBounds(50,200,50,50);  
        b2=new JButton("-");  
        b2.setBounds(120,200,50,50);  
        b1.addActionListener(this);  
        b2.addActionListener(this);  
        f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);  
        f.setSize(300,300);  
        f.setLayout(null);  
        f.setVisible(true);  
    }         
   
 public void actionPerformed(ActionEvent e) {  
        String s1=tf1.getText();  
        String s2=tf2.getText();  
        int a=Integer.parseInt(s1);  
        int b=Integer.parseInt(s2);  
        int c=0;  
        if(e.getSource()==b1){  
            c=a+b;  
        }else if(e.getSource()==b2){  
            c=a-b;  
        }  
        String result=String.valueOf(c);  
        tf3.setText(result);  
    }  
public static void main(String[] args) {  
    new TextFieldExample();  
} }  
import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    JButton b=new JButton("Click Here");  
    b.setBounds(50,100,95,30);  
    f.add(b);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}   }  
Java JButton Example with ActionListener
import java.awt.event.*;  
import javax.swing.*;    
public class ButtonExample {  
public static void main(String[] args) {  
    JFrame f=new JFrame("Button Example");  
    final JTextField tf=new JTextField();  
    tf.setBounds(50,50, 150,20);  
    JButton b=new JButton("Click Here");  
    b.setBounds(50,100,95,30);  
    b.addActionListener(new ActionListener(){  
public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to MCC");  
        }      });  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  }  
Example of displaying image on the button:
import javax.swing.*;      
public class ButtonExample{    
ButtonExample(){    
JFrame f=new JFrame("Button Example");            
JButton b=new JButton(new ImageIcon("D:\\icon.png"));    
b.setBounds(100,100,100, 40);    
f.add(b);    
f.setSize(300,400);    
f.setLayout(null);    
f.setVisible(true);    
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    
    }         
public static void main(String[] args) {    
    new ButtonExample();    
}     }    
JToggleButton Example
import java.awt.FlowLayout;  
import java.awt.event.ItemEvent;  
import java.awt.event.ItemListener;  
import javax.swing.JFrame;  
import javax.swing.JToggleButton;  
  public class JToggleButtonExample extends JFrame implements ItemListener {  
    public static void main(String[] args) {  
        new JToggleButtonExample();       }  
    private JToggleButton button;  
    JToggleButtonExample() {  
        setTitle("JToggleButton with ItemListener Example");  
        setLayout(new FlowLayout());  
        setJToggleButton();  
        setAction();  
        setSize(200, 200);  
        setVisible(true);  
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       }  
 private void setJToggleButton() {  
        button = new JToggleButton("ON");  
        add(button);  
    }  
    private void setAction() {  
        button.addItemListener(this);  
    }  
    public void itemStateChanged(ItemEvent eve) {  
        if (button.isSelected())  
            button.setText("OFF");  
        else  
            button.setText("ON");  
    }  
}  
Java JCheckBox Example
import javax.swing.*;  
public class CheckBoxExample  
{  
     CheckBoxExample(){  
        JFrame f= new JFrame("CheckBox Example");  
        JCheckBox checkBox1 = new JCheckBox("C++");  
        checkBox1.setBounds(100,100, 50,50);  
        JCheckBox checkBox2 = new JCheckBox("Java", true);  
        checkBox2.setBounds(100,150, 50,50);  
        f.add(checkBox1);  
        f.add(checkBox2);  
        f.setSize(400,400);  
        f.setLayout(null);  
        f.setVisible(true);        }  
public static void main(String args[])  
    {  
    new CheckBoxExample();  
    }}  
Java JCheckBox Example with ItemListener
import javax.swing.*;  
import java.awt.event.*;    
public class CheckBoxExample    
{    
     CheckBoxExample(){    
        JFrame f= new JFrame("CheckBox Example");    
        final JLabel label = new JLabel();            
        label.setHorizontalAlignment(JLabel.CENTER);    
        label.setSize(400,100);    
        JCheckBox checkbox1 = new JCheckBox("C++");    
        checkbox1.setBounds(150,100, 50,50);    
        JCheckBox checkbox2 = new JCheckBox("Java");    
        checkbox2.setBounds(150,150, 50,50);    
        f.add(checkbox1); f.add(checkbox2); f.add(label);    
        checkbox1.addItemListener(new ItemListener() {    
             public void itemStateChanged(ItemEvent e) {                              
   label.setText("C++ Checkbox: "     
                + (e.getStateChange()==1?"checked":"unchecked"));    
             }             });    
      
  checkbox2.addItemListener(new ItemListener() {    
             public void itemStateChanged(ItemEvent e) {              
   
                label.setText("Java Checkbox: "     
                + (e.getStateChange()==1?"checked":"unchecked")); 
   
             }    
          });    
        f.setSize(400,400);    
        f.setLayout(null);    
        f.setVisible(true);    
     }    
public static void main(String args[])    
{    
    new CheckBoxExample();    
}    
}    
Case study / Homework / Assignment – shopping
cart.

Build a Shopping cart with appropriate


requirements and assumptions.
Java JRadioButton Example with ActionListener
import javax.swing.*;    
import java.awt.event.*;    
class RadioButtonExample extends JFrame implements ActionListener
{    
JRadioButton rb1,rb2;    
JButton b;    
RadioButtonExample(){      
rb1=new JRadioButton("Male");    
rb1.setBounds(100,50,100,30);      
rb2=new JRadioButton("Female");    
rb2.setBounds(100,100,100,30);    
ButtonGroup bg=new ButtonGroup();    
bg.add(rb1);bg.add(rb2);    
b=new JButton("click");    
b.setBounds(100,150,80,30);    
b.addActionListener(this);    
add(rb1);add(rb2);add(b);    
setSize(300,300);    setLayout(null);    setVisible(true);    }    
public void actionPerformed(ActionEvent e){    
if(rb1.isSelected()){    
JOptionPane.showMessageDialog(this,"You are Male.");    
}    
if(rb2.isSelected()){    
JOptionPane.showMessageDialog(this,"You are Female.");    
}    
}    
public static void main(String args[]){    
new RadioButtonExample();    

}}   
JViewport
• The JViewport class is used to implement
scrolling. JViewport is designed to support both
logical scrolling and pixel-based scrolling. The
viewport's child, called the view, is scrolled by
calling the JViewport.setViewPosition() method.

JTabbedPane
• The JTabbedPane class is used to switch between
a group of components by clicking on a tab with a
given title or icon. It inherits JComponent class.
import javax.swing.*;  
public class TabbedPaneExample {  
JFrame f;  
TabbedPaneExample(){  
    f=new JFrame();  
    JTextArea ta=new JTextArea(200,200);  
    JPanel p1=new JPanel();  
    p1.add(ta);  
    JPanel p2=new JPanel();  
    JPanel p3=new JPanel();  
    JTabbedPane tp=new JTabbedPane();  
    tp.setBounds(50,50,200,200);  
    tp.add("main",p1);   public static void main(String[] 
    tp.add("visit",p2);   args) {  
    tp.add("help",p3);         new TabbedPaneExample();  
}}  
    f.add(tp);  
    f.setSize(400,400);  
    f.setLayout(null);      f.setVisible(true);  }  
import java.awt.*;  
import javax.swing.*;  
public class ViewPortClass2 {  
    public static void main(String[] args) {  
        JFrame frame = new JFrame("Tabbed Pane Sample");  
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  
        JLabel label = new JLabel("Label");  
        label.setPreferredSize(new Dimension(1000, 1000));  
        JScrollPane jScrollPane = new JScrollPane(label);  
  
        JButton jButton1 = new JButton();  
        jScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZO
NTAL_SCROLLBAR_ALWAYS);  
        jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_
SCROLLBAR_ALWAYS);  
        jScrollPane.setViewportBorder(new LineBorder(Color.RED));
  
        jScrollPane.getViewport().add(jButton1, null);  
frame.add(jScrollPane, BorderLayout.CENTER);  
        frame.setSize(400, 150);  
        frame.setVisible(true);  
    }  
}  
Java JScrollBar Example with AdjustmentListener
import javax.swing.*;  
import java.awt.event.*;  
class ScrollBarExample  
{  
ScrollBarExample(){  
    JFrame f= new JFrame("Scrollbar Example");  
    final JLabel label = new JLabel();          
    label.setHorizontalAlignment(JLabel.CENTER);    
    label.setSize(400,100);  
    final JScrollBar s=new JScrollBar();  
    s.setBounds(100,100, 50,100);  
    f.add(s); f.add(label);  
    f.setSize(400,400);  
   f.setLayout(null);  
   f.setVisible(true);  
   s.addAdjustmentListener(new AdjustmentListener() {  
   
 public void adjustmentValueChanged(AdjustmentEvent e) {  
       label.setText("Vertical Scrollbar value is:"+ s.getValue());  
    }  
 });  
}  
public static void main(String args[])  
{  
   new ScrollBarExample();  
}}  
Java JSlider Example: painting ticks
import javax.swing.*;  
public class SliderExample extends JFrame{  
public SliderExample() {  
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);  
slider.setMinorTickSpacing(2);  
slider.setMajorTickSpacing(10);  
slider.setPaintTicks(true);  
slider.setPaintLabels(true);  
  
JPanel panel=new JPanel();  
panel.add(slider);  
add(panel);  
}  
public static void main(String s[]) {  
SliderExample frame=new SliderExample();  
frame.pack();  
frame.setVisible(true);  
}  }  
Java JList Example with ActionListener
import javax.swing.*;  
import java.awt.event.*;  
public class ListExample  
{  
     ListExample(){  
        JFrame f= new JFrame();  
        final JLabel label = new JLabel();          
        label.setSize(500,100);  
        JButton b=new JButton("Show");  
        b.setBounds(200,150,80,30);  
        final DefaultListModel<String> l1 = new DefaultListModel<
>();  
          l1.addElement("C");  
          l1.addElement("C++");   public static void main(String args[])
          l1.addElement("Java");     
    {  
          l1.addElement("PHP");  
   new ListExample();  
               }}  
final JList<String> list1 = new JList<>(l1);  
          list1.setBounds(100,100, 75,75);  
          DefaultListModel<String> l2 = new DefaultListModel<>();  
          l2.addElement("Turbo C++");  
          l2.addElement("Struts");  
          l2.addElement("Spring");  
          l2.addElement("YII");  
          final JList<String> list2 = new JList<>(l2);  
          list2.setBounds(100,200, 75,75);  
          f.add(list1); f.add(list2); f.add(b); f.add(label);  
          f.setSize(450,450);  
          f.setLayout(null);  
          f.setVisible(true);  
          b.addActionListener(new ActionListener() {  
              public void actionPerformed(ActionEvent e) {   
                 String data = "";  
                 if (list1.getSelectedIndex() != -1) {                       
                    data = "Programming language Selected: " + list1.getSelected
Value();   
                    label.setText(data);  
                 }  
 if(list2.getSelectedIndex() != -1){  
                    data += ", FrameWork Selected: ";  
                    for(Object frame :list2.getSelectedValues()){  
                       data += frame + " ";  
                    }  
                 }  
                 label.setText(data);  
              }  
           });   
     }  
public static void main(String args[])  
    {  
   new ListExample();  

    }}  
Java JTable Example with ListSelectionListener
import javax.swing.*;    
import javax.swing.event.*;  
public class TableExample {    
      public static void main(String[] a) {  
            JFrame f = new JFrame("Table Example");  
            String data[][]={ {"101","Amit","670000"},    
                                                                       {"102","Jai","78
0000"},    
                                                                       {"101","Sachin"
,"700000"}};    
                            String column[]={"ID","NAME","SALARY"};    
     
                            final JTable jt=new JTable(data,column);    
            jt.setCellSelectionEnabled(true);  
            ListSelectionModel select= jt.getSelectionModel();  
            select.setSelectionMode(ListSelectionModel.SINGLE_SELE
CTION);  
           
 select.addListSelectionListener(new ListSelectionListener() {  
              public void valueChanged(ListSelectionEvent e) {  
                String Data = null;  
                int[] row = jt.getSelectedRows();  
                int[] columns = jt.getSelectedColumns();  
                for (int i = 0; i < row.length; i++) {  
                  for (int j = 0; j < columns.length; j++) {  
                    Data = (String) jt.getValueAt(row[i], columns[j]);  
                  } }  
                System.out.println("Table element selected is: " + Dat
a);    
              }       
            });  
            JScrollPane sp=new JScrollPane(jt);    
            f.add(sp);  
            f.setSize(300, 200);  
            f.setVisible(true);  
          }           }  
If you select an element in column NAME, name of the element will be
displayed on the console:

Table element selected is: Sachin  
Java JTree Example
import javax.swing.*;  
import javax.swing.tree.DefaultMutableTreeNode;  
public class TreeExample {  
JFrame f;  
TreeExample(){  
    f=new JFrame();   
    DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");  
    DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");  
    DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");  
    style.add(color);  
    style.add(font);  
    DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");  
    DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");  
    DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");  
    DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");  
    color.add(red); color.add(blue); color.add(black); color.add(green);      
    
JTree jt=new JTree(style);  
    f.add(jt);  
    f.setSize(200,200);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new TreeExample();  
}}  
Java JComboBox Example with ActionListener
import javax.swing.*;    
import java.awt.event.*;    
public class ComboBoxExample {    
JFrame f;    
ComboBoxExample(){    
    f=new JFrame("ComboBox Example");   
    final JLabel label = new JLabel();          
    label.setHorizontalAlignment(JLabel.CENTER);  
    label.setSize(400,100);  
    JButton b=new JButton("Show");  
    b.setBounds(200,100,75,20);  
    String languages[]={"C","C++","C#","Java","PHP"};        
    final JComboBox cb=new JComboBox(languages);    
    cb.setBounds(50, 100,90,20);    
    f.add(cb); f.add(label); f.add(b);    
    f.setLayout(null);    
 
   f.setSize(350,350);    
    f.setVisible(true);       
    b.addActionListener(new ActionListener() {  
        public void actionPerformed(ActionEvent e) {       
String data = "Programming language Selected: "   
   + cb.getItemAt(cb.getSelectedIndex());  
label.setText(data);  
}  
});           
}    
public static void main(String[] args) {    
    new ComboBoxExample();         
}    

}    
Java LayoutManagers

The LayoutManagers are used to arrange


components in a particular manner.
LayoutManager is an interface that is
implemented by all the classes of layout
managers. There are following classes that
represents the layout managers:
• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• javax.swing.BoxLayout
• javax.swing.GroupLayout
• javax.swing.ScrollPaneLayout
• javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the
components in five regions: north, south, east,
west and center. Each region (area) may contain
one component only. It is the default layout of
frame or window. The BorderLayout provides five
constants for each region:
• public static final int NORTH
• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER
import java.awt.*;  
import javax.swing.*;  
 public class Border {  
JFrame f;  
Border(){  
    f=new JFrame();  
    JButton b1=new JButton("NORTH");;  
    JButton b2=new JButton("SOUTH");;  
    JButton b3=new JButton("EAST");;  
    JButton b4=new JButton("WEST");;  
    JButton b5=new JButton("CENTER");;  
    f.add(b1,BorderLayout.NORTH);  
    f.add(b2,BorderLayout.SOUTH);  
    f.add(b3,BorderLayout.EAST);  
    f.add(b4,BorderLayout.WEST);  
    f.add(b5,BorderLayout.CENTER);  
    f.setSize(300,300);  
    f.setVisible(true);   }  
public static void main(String[] args) {  
    new Border();  
}  
}  
Java FlowLayout
The FlowLayout is used to arrange the components
in a line, one after another (in a flow). It is the
default layout of applet or panel.
Fields of FlowLayout class
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
import java.awt.*;  
import javax.swing.*;  
public class MyFlowLayout{  
JFrame f;  
MyFlowLayout(){  
    f=new JFrame();  
    JButton b1=new JButton("1");  
    JButton b2=new JButton("2");  
    JButton b3=new JButton("3");  
    JButton b4=new JButton("4");  
    JButton b5=new JButton("5");  
    f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
    f.setLayout(new FlowLayout(FlowLayout.RIGHT));  
    //setting flow layout of right alignment  
  
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new MyFlowLayout();  
}  
}  
Java GridLayout
The GridLayout is used to arrange the components
in rectangular grid. One component is displayed
in each rectangle.
import java.awt.*;  
import javax.swing.*;  
  
public class MyGridLayout{  
JFrame f;  
MyGridLayout(){  
    f=new JFrame();  
      
    JButton b1=new JButton("1");  
    JButton b2=new JButton("2");  
    JButton b3=new JButton("3");  
    JButton b4=new JButton("4");  
    JButton b5=new JButton("5");  
        JButton b6=new JButton("6");  
        JButton b7=new JButton("7");  
    JButton b8=new JButton("8");  
        JButton b9=new JButton("9");  
          
   
 f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);  
    f.add(b6);f.add(b7);f.add(b8);f.add(b9);  
  
    f.setLayout(new GridLayout(3,3));  
    //setting grid layout of 3 rows and 3 columns  
  
    f.setSize(300,300);  
    f.setVisible(true);  
}  
public static void main(String[] args) {  
    new MyGridLayout();  
}  
}  
JMenuBar, JMenu and JMenuItem
• The JMenuBar class is used to display menubar
on the window or frame. It may have several
menus.
• The object of JMenu class is a pull down menu
component which is displayed from the menu
bar. It inherits the JMenuItem class.
• The object of JMenuItem class adds a simple
labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its
subclass.
import javax.swing.*;  
class MenuExample  
{  
          JMenu menu, submenu;  
          JMenuItem i1, i2, i3, i4, i5;  
          MenuExample(){  
          JFrame f= new JFrame("Menu and MenuItem Example");  
          JMenuBar mb=new JMenuBar();  
          menu=new JMenu("Menu");  
          submenu=new JMenu("Sub Menu");  
          i1=new JMenuItem("Item 1");  
          i2=new JMenuItem("Item 2");  
          i3=new JMenuItem("Item 3");  
          i4=new JMenuItem("Item 4");  
          i5=new JMenuItem("Item 5");  
          menu.add(i1); menu.add(i2); menu.add(i3);  
          submenu.add(i4); submenu.add(i5);  
          
menu.add(submenu);  
          mb.add(menu);  
          f.setJMenuBar(mb);  
          f.setSize(400,400);  
          f.setLayout(null);  
          f.setVisible(true);  
}  
public static void main(String args[])  
{  
new MenuExample();  
}}  
Self Study –

Layered Panes
Split Panes
Windows,
Desktop Panes,
Inner Frames and Dialog Boxes,
Images.

You might also like