[go: up one dir, main page]

0% found this document useful (0 votes)
43 views27 pages

Swing

Uploaded by

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

Swing

Uploaded by

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

CSE 1203

Object Oriented Programming

Java GUI Programming -01


Java: Swing
Java: swing 2 Java: awt vs swing
Java Swing is a part of Java Foundation Classes (JFC) that
is used to create window-based applications. It is built on
the top of AWT (Abstract Windowing Toolkit) API and
entirely written in java.
The javax.swing package provides classes for java swing
API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Java: Hierarchy of Swing classes Java: swing topics


3

Creating Frame:
JFrame
Java: JFrame
Java swing: JFrame class 4 Java: swing methods
The class JFrame is an extended version of java.awt.Frame that adds
support for the JFC/Swing component architecture. It is like a board where
you can add your swing objects

Java swing Frame: ways to create frame


Methods:
1. By creating the object of Frame class (association)
2. By extending Frame class (inheritance)
3. Create a frame using Swing inside main()

Java swing Frame: way 1 to create frame


package CSE1203; // setting close operation
import javax.swing.JFrame; frame.setDefaultCloseOperation(JFrame.EXIT_ON_C
import javax.swing.*; LOSE);

public class First { // sets 500 width and 600 height


JFrame frame; frame.setSize(500, 600);
First()
{ // makes the frame visible
frame=new JFrame("first way"); frame.setVisible(true);
}
public static void main(String[] args) {
Notes A frame frame object is created in the constructor of new First(); //anonymous object
First class. For JFrame class import javax.swing.JFrame; //First f=new First() is similar
}
}
Java: JFrame
Java swing Frame: way 2 to create frame 5 Java swing Frame: way 3 to create frame
package CSE1203; package CSE1203;
import javax.swing.*; import javax.swing.JFrame;
public class First {
public class First extends JFrame { public static void main(String[] args) {
JFrame frame=new JFrame("CSE 1203");
First() frame.setSize(600,400);
{ frame.setLocation(200,100);
setTitle("this is also a title"); //frame.setBounds(200,100,200,300);
// setting close operation frame.setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(frame.EXIT_ON_C
LOSE);
setSize(400, 500);
}
setVisible(true); }
}
public static void main(String[] args) Notes A frame of size 600x400 will be created at location
{ display point (200,100). The frame is visible and it would be
First f=new First() is similar closed when x button is clicked.
}
}

Notes here First class is inherited by Jframe class. So object


of Jframe class can use the methods of Jframe class. The
methods includes setTitle(), setSize(), setVisible
etc.
getContentPane()
6
ImageIcon
Color(color)
setResizable()

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import java.awt.Color;
import java.awt.Container;
Java: ImageIcon
7

Java AWT : Container


The Container is a component in AWT that can contain
another components like buttons, textfields, labels etc. The
classes that extends Container class are known as container
such as Frame, Dialog and Panel.

It is basically a screen where the where the components are


placed at their specific locations. Thus it contains and
controls the layout of components.

Container c=frame.getContentPane();
c.setBackground(Color.RED); Java swing : JFrame setResizable()
//create color object frame.setResizable(false);
//Color color=new Color(255,0,0)
Notes If the argument is false, the frame cann’t be resized.
//c.setBackground(color);
Notes To change the background of the frame, first create a
Container class object then set its background color using
Color class
Jlabel8

Font
setText()
setFont()
add()

import java.awt.Font;
import javax.swing.JLabel
Java: JLabel
Java swing : Jlabel class 9 Java swing : Font class
JFrame frame=new JFrame("JLabel"); Font font=new Font("Arial",Font.PLAIN,12);
frame.setBounds(200, 100,400,300); label.setFont(font);
frame.setVisible(true); Notes Font class constructor requires three parameters like
Font name, Font type and Font size
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c=frame.getContentPane();
c.setLayout(null); Java swing : ImageIcon with JLabel class
JLabel label=new JLabel("Username:");
//label.setText(“User Name:”); ImageIcon icon=new
label.setBounds(50,70,100,30); ImageIcon("F:\\Zaman\\Image\\Apple.png");
c.add(label); JLabel label=new
JLabel("Apple",icon,JLabel.LEFT);
label.setBounds(50,70,500,200);
c.add(label);
frame.setVisible(true);

Notes Jlabel constructor take 3 arguments text, icon and position

Java swing : Jlabel add image


ImageIcon image=new ImageIcon("F:\\Zaman\\Image\\Apple.png");
JLabel label=new JLabel(image);
c=this.getContentPane();
c.setLayout(null);
label.setBounds(100,178,image.getIconWidth(),image.getIconHeight());
c.add(label);
JTextField
JPasswordField
10

setText()
setEditable()
setForeground()
setBackground()
setEchoChar()

import javax.swing.JTextField
import javax.swing.JPasswordField
Java: JTextField & JPasswordField
Java swing : JTextField
JTextField text=new JTextField();
text.setText("type here");
text.setBounds(50,30,100,20);
text.setForeground(Color.blue);
text.setBackground(Color.cyan);
text.setEditable(true);
c.add(text);
Notes: JTextField() is a input box

Java swing : JPasswordText class


JPasswordField text=new JPasswordField();
text.setBounds(50,30,100,20);
text.setForeground(Color.blue);
text.setBackground(Color.cyan);
text.setEchoChar('*');
text.setEchoChar((char)0); //show
text.setEditable(true);
c.add(text);
JButton
12
JCursor
setBounds()
setCursor()

import javax.swing.JButton
import java.awt.Cursor
Java: JTextField & JPasswordField
Java swing : JButton & Cursor class
JButton btn=new JButton("Submit");
btn.setBounds(100,50,100,30);
Cursor cursor=new Cursor(Cursor.HAND_CURSOR);
btn.setCursor(cursor);
btn.setEnabled(false);
c.add(btn);
Notes when cursor moves inside button Hand cursor is
displayed. To disable the button use setEnabled() to
false
Java: JRadioButton
Java swing : JRadioButton is used to select one from many
JRadioButton rb1=new JRadioButton();
Notes ButtonGroup() : Use to
JRadioButton rb2=new JRadioButton(); create a group, in which we can
ButtonGroup bg=new ButtonGroup(); add JRadioButton. We can
select only one JRadioButton in
rb1.setBounds(400,200,70,30); a ButtonGroup.
rb1.setText("Male");
rb1.setBackground(color);
c.add(rb1);

rb2.setBounds(400,240,70,30);
rb2.setText("Female");
rb2.setBackground(color);
c.add(rb2);

bg.add(rb1);
bg.add(rb2);
Java: JCheckBox & JTextArea
Java swing : JCheckBox
JCheckBox cb=new JCheckBox(); Notes The JCheckBox class is used to
create a checkbox. It is used to turn an
cb.setBounds(400,340,70,30); option on (true) or off (false). Clicking on a
cb.setText("Agree"); CheckBox changes its state from "on" to
cb.setBackground(color); "off" or from "off" to "on ".It
inherits JToggleButton class.
c.add(cb);

Java swing : JTextArea


JTextArea txt=new JTextArea(); The object of a JTextArea
class is a multi line region
c=this.getContentPane(); that displays text. It allows
c.setLayout(null); the editing of multiple line
txt.setBounds(100,10,400,300); text. It inherits
txt.setBackground(Color.RED); JTextComponent class
c.add(txt);
Java: JTable
The JTable class is used to display data in tabular form. It is composed of
rows and columns.
JTable jt;
String data[][]={
{"100","Belal","1200"},
{"200","Aslam","1700"},
{"300","Kamal","1100"},
{"800","Kamal","9000"}
};
String columns[]={"AcN-","-Name-","-Balance-"};
//inside constructor
jt=new JTable(data,columns);
jt=new JTable(data,columns);
jt.setBounds(50,50,250,270);
jt.setFont(font);
c.add(jt);
Java: JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
JTable jt;
String data[][]={
{"100","Belal","1200"},
{"200","Aslam","1700"},
{"300","Kamal","1100"},
{"800","Kamal","9000"}
};
String columns[]={"AcN-","-Name-","-Balance-"};
//inside constructor
jt=new JTable(data,columns);
//jt.setBounds(50,50,250,270);
//jt.setFont(font);
//c.add(jt);
JScrollPane sp=new JScrollPane(jt);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLL
BAR_ALWAYS);
sp.setBounds(50,50,250,170);
c.add(sp);
Java: JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the user can choose either one item or multiple items. It inherits JComponent class.
JList jl;
String days[]={"Sunday","Monday","Tuesday","Wednesday","Thursday"};
jl=new JList(days);
jl=new JList(days);
jl.setBounds(50,50,100,100);
jt.setFont(font);
c.add(jl);

Adding Scroll Bar


JList jl;
String days[]={"Sunday","Monday","Tuesday","Wednesday","Thursday"};
jl=new JList(days);
jl=new JList(days);
JScrollPane sp=new JScrollPane(jl);
sp.setBounds(50,50,70,70);
c.add(sp);
Java: JComboBox
JComboBox shows a popup menu that shows a list and the user can select a option from
that specified list .
DefaultComboBoxModel cb=new DefaultComboBoxModel<>();
//inside constructor
cb.addElement("Dhaka");
cb.addElement("Rajshahi");
JComboBox jcb=new JComboBox<>(cb);
jcb.setBounds(50,50,100,40);
jcb.setSelectedIndex(0);
c.add(jcb);

Another approach
String days[]={"Sunday","Monday","Tuesday","Wednesday","Thursday"};
JComboBox cb=new JComboBox<>(days);
//inside constructor
cb.setBounds(50,50,100,30);
cb.setSelectedIndex(1);
cb.setEditable(true);
c.add(cb);
Java: inheritance
20 Java swing : ActionListener
The Java ActionListener is notified whenever you
click on the button or menu item. It is notified
against ActionEvent. The ActionListener interface is
found in java.awt.event package. It has only one
method: actionPerformed().

Java swing : actionPerformed() method


The actionPerformed() method is invoked
automatically whenever you click on the registered
component.
public abstract void actionPerformed(ActionEvent e);

Java swing :How to implement ActionListener


ActionListener class, you need to follow 3 steps:
1) Implement the ActionListener interface in the class:
public class ActionListenerExample Implements
ActionListener
2) Register the component with the Listener:
component.addActionListener(instanceOfListenerclass);

3) Override the actionPerformed() method:


public void actionPerformed(ActionEvent e){
//Write the code here
}
Java: inheritance
Java swing : use of ActionListener interface
21
package CSE1203; public void actionPerformed(ActionEvent e) {
if(e.getSource()==btn1)
import java.awt.Color; label.setText("Submit Button Pressed");
import java.awt.Container; if(e.getSource()==btn2)
import java.awt.Cursor; label.setText("Cancel Button Pressed");
import java.awt.Font; }
import java.awt.Image; }
import java.awt.event.ActionEvent; public class First {
import java.awt.event.ActionListener; public static void main(String[] args)
import java.util.List; {
MyFrame frame=new MyFrame();
import javax.swing.*; frame.setBounds(200, 100,400,500);
class MyFrame extends JFrame implements frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ActionListener{ frame.setVisible(true);
Container c;
JButton btn1,btn2; }
JLabel label; }
public MyFrame() {
c=this.getContentPane(); Notes: When a button is clicked, through
c.setLayout(null); addActionListener() method it invokes
btn1=new JButton("Submit"); actionPerformed() automatically. Using object e
btn1.setBounds(100,50,100,30); inside the actionPerformed() method check which
btn2=new JButton("Cancel"); button is clicked and setText() in label
btn2.setBounds(210,50,100,30); accordingly.
label=new JLabel();
label.setBounds(110,110,400,30);
label.setText("Output Displays here");
btn1.addActionListener(this);
btn2.addActionListener(this);
Java: inheritance
Java swing : use of ActionListener interface
22
package CSE1203; btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
import java.awt.Color; label.setText("Submit is pressed");
import java.awt.Container; }
import java.awt.Cursor; });
import java.awt.Font; btn2.addActionListener(new ActionListener() {
import java.awt.Image; public void actionPerformed(ActionEvent e) {
import java.awt.event.ActionEvent; label.setText("Cancel is pressed");
import java.awt.event.ActionListener; }
import java.util.List; });
c.add(btn1);
import javax.swing.*; c.add(btn2);
class MyFrame extends JFrame{ c.add(label);
Container c; }
JButton btn1,btn2; }
JLabel label; public class First {
public MyFrame() { public static void main(String[] args) {
c=this.getContentPane(); MyFrame frame=new MyFrame();
c.setLayout(null); frame.setBounds(200, 100,400,500);
btn1=new JButton("Submit"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn1.setBounds(100,50,100,30); frame.setVisible(true);
btn2=new JButton("Cancel"); }
btn2.setBounds(210,50,100,30); }
label=new JLabel();
label.setBounds(110,110,400,30); Notes: When AddActionListener is called, its
label.setText("Output Displays here"); parameter is the object of interface and in the
same time abstract method actionPermored() is
overrriden. Here no need to create a class to
override actionPerformed().
Java: Swing Example
Java swing : login form 23
package CSE1203; label2=new JLabel("Password"); public void actionPerformed(ActionEvent
e) {
import java.awt.Color; label2.setBounds(50,80,100,30); int flag=0;
import java.awt.Container; pass1=new JPasswordField(); String s=new
import java.awt.Cursor; String(pass1.getPassword());
import java.awt.Font; pass1.setBounds(120,80,180,30); if(e.getSource()==btn1)
import java.awt.Image; dispose(); //close the frame
import java.awt.event.ActionEvent; btn1=new JButton("Cancel"); if(e.getSource()==btn2) {
import java.awt.event.ActionListener; for(int i=0;i<username.length;i++) {
import java.util.List; btn1.setBounds(100,150,100,30); if(username[i].equals(text1.getText()))
btn2=new JButton("Login"); if(password[i].equals(s))
import javax.swing.*; flag++;
class MyFrame extends JFrame btn2.setBounds(210,150,100,30); }
implements ActionListener{ if(flag==1)
Container c; label9=new JLabel(); label9.setText("Valid User");
JButton btn1,btn2; else
JLabel label1,label2,label9; label9.setBounds(120,200,180,30); label9.setText("Worng
JTextField text1,text2; username/password");
JPasswordField pass1; btn1.addActionListener(this); }
btn2.addActionListener(this); }
String[] username= {"zaman","kamal"}; }
String[] password= {"123","user"}; c.add(label1); public class First {
c.add(text1); public static void main(String[]
public MyFrame() { c.add(label2); args) {
c=this.getContentPane(); c.add(pass1); MyFrame frame=new MyFrame();
c.setLayout(null); c.add(btn1); frame.setBounds(200,
c.add(btn2); 100,400,500);
label1=new JLabel("Username"); c.add(label9); frame.setDefaultCloseOperation(JFrame.E
} XIT_ON_CLOSE);
label1.setBounds(50,50,100,30); frame.setVisible(true);
text1=new JTextField(); }
}
text1.setBounds(120,50,180,30);
Java: Swing
Java swing : JTextArea class public MyFrame() {
c=this.getContentPane();
c=this.getContentPane(); c.setLayout(null);
c.setLayout(null); rb1=new JRadioButton("Male");
JTextArea area=new JTextArea(); rb1.setBounds(100,50,200,30);
rb1.setSelected(true)
area.setBounds(100,50,200,150);
rb2=new JRadioButton("Female");
area.setBackground(Color.BLUE); rb2.setBounds(100,80,200,30);
area.setForeground(Color.white); ButtonGroup bg=new ButtonGroup();
area.setLineWrap(true); bg.add(rb1); bg.add(rb2);
c.add(area); rb1.addActionListener(this);
rb2.addActionListener(this);
c.add(rb1); c.add(rb2);
Notes This method is used to input a text in a text area. }
public void actionPerformed(ActionEvent e) {
if(rb1.isSelected()){
Java swing : JRadioButton & ButtonGroup class JOptionPane.showMessageDialog(this,"You are
package CSE1203; Male.");
}
import java.awt.Color; if(rb2.isSelected()){
import java.awt.Container; JOptionPane.showMessageDialog(this,"You are
import java.awt.event.ActionEvent; Female.");
import java.awt.event.ActionListener; }
import javax.swing.*; }
}
class MyFrame extends JFrame implements public class First {
ActionListener{ public static void main(String[] args) {
Container c; MyFrame frame=new MyFrame();
JRadioButton rb1,rb2; frame.setBounds(200, 100,400,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Notes ButtonGroup class combines the buttons in one group frame.setVisible(true);
ie only one can be selected from the group. }
}
Java: Swing
Java swing : JcheckBox class
package CSE1203; public class First {
import java.awt.Container; public static void main(String[] args)
import java.awt.event.ActionEvent; {
import java.awt.event.ActionListener; MyFrame frame=new MyFrame();
import javax.swing.*; frame.setBounds(200, 100,400,500);
class MyFrame extends JFrame implements frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE
ActionListener{ );
Container c; frame.setVisible(true);
JCheckBox check;
JButton btn1,btn2; }
public MyFrame() { }
c=this.getContentPane();
c.setLayout(null); Notes Initially Next Button is disabled. When check box is
check=new JCheckBox("I agree"); selected then Next button would be enabled.
check.setBounds(100,80,200,30);
btn1=new JButton("Cancel");
btn1.setBounds(100,130,80,30);
btn2=new JButton("Next");
btn2.setBounds(180,130,80,30);
btn2.setEnabled(false);
check.addActionListener(this);
c.add(check); c.add(btn1); c.add(btn2);
}
public void actionPerformed(ActionEvent e) {
if(check.isSelected())
btn2.setEnabled(true);
else
btn2.setEnabled(false);
}
}
Java: Swing
Java swing : JComboBox class
package CSE1203; Notes There are two arrays ax and bx contains contry and
import java.awt.Container; capital name respectively. When user select a country from
import java.awt.event.ActionEvent; combobox then in the actionPerformed() method selected
import java.awt.event.ActionListener; country index is stored in i. Finally, capital bx[i] is displayed
import javax.swing.*; in dialog box.
class MyFrame extends JFrame implements The main() method is NOT written here, it is
ActionListener{ similar to the previous one.
Container c;
JComboBox combo;
String[] ax= Java swing : JMenuBar class
{"Australia","Banglades","India","Japan","Malays
ia"};
String[] bx= {"Canberra","Dhaka","New
Delhi","Tokyo","Kualalumpur"};
public MyFrame() {
c=this.getContentPane();
c.setLayout(null);
combo=new JComboBox(ax);
combo.setSelectedIndex(1);
combo.setBounds(100,80,200,30);
combo.addActionListener(this);
c.add(combo);
}
public void actionPerformed(ActionEvent e) {
//String s=(String) combo.getSelectedItem();
int i=combo.getSelectedIndex();
JOptionPane.showMessageDialog(this,"Capital:"+bx
[i]);
}
}
27

THANK YOU

You might also like