Introduction to Swing - Bapatla Engineering College to Swing.pdf · Java. Because the AWT...

22
Introducing Swing The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but limited graphical interface. One reason for the limited nature of the AWT is that it translates its various visual components into their corresponding, platform-specific equivalents, or peers. This means that the look and feel of a component is defined by the platform, not by Java. Because the AWT components use native code resources, they are referred to as heavyweight. The use of native peers led to several problems. First, because of variations between operating systems, a component might look, or even act, differently on different platforms. This potential variability threatened the philosophy of Java: write once, run anywhere. Second, the look and feel of each component was fixed (because it is defined by the platform) and could not be (easily) changed. Third, the use of heavyweight components caused some restrictions like a heavyweight component is always rectangular and opaque. Swing was included as part of the Java Foundation Classes (JFC). Beginning with Java 1.2, Swing (and the rest of the JFC) was Swing does not replace AWT. Instead, Swing is built on the foundation of the AWT. This is why the AWT is still a crucial part of Java. Swing also uses the same event handling mechanism as the AWT. Two Key Swing Features: Swing was created to address the limitations present in the AWT. It does this through two key features: lightweight components and a pluggable look and feel. Together they provide an elegant, yet easy-to-use solution to the problems of the AWT. More than anything else, it is these two features that define the essence of Swing. Some of the Swing Components And Examples: JLabel: With the JLabel class, one can display unselectable text and images. To create a component that displays a string, an image, or both, one can do so by using or extending JLabel.

Transcript of Introduction to Swing - Bapatla Engineering College to Swing.pdf · Java. Because the AWT...

Introducing Swing The AWT defines a basic set of controls, windows, and dialog boxes that support a

usable, but limited graphical interface. One reason for the limited nature of the AWT is that it

translates its various visual components into their corresponding, platform-specific equivalents,

or peers. This means that the look and feel of a component is defined by the platform, not by

Java. Because the AWT components use native code resources, they are referred to as

heavyweight.

The use of native peers led to several problems. First, because of variations between

operating systems, a component might look, or even act, differently on different platforms. This

potential variability threatened the philosophy of Java: write once, run anywhere. Second, the

look and feel of each component was fixed (because it is defined by the platform) and could not

be (easily) changed. Third, the use of heavyweight components caused some restrictions like a

heavyweight component is always rectangular and opaque. Swing was included as part of the

Java Foundation Classes (JFC). Beginning with Java 1.2, Swing (and the rest of the JFC) was

Swing does not replace AWT. Instead, Swing is built on the foundation of the AWT.

This is why the AWT is still a crucial part of Java. Swing also uses the same event handling

mechanism as the AWT.

Two Key Swing Features:

Swing was created to address the limitations present in the AWT. It does this through two

key features: lightweight components and a pluggable look and feel. Together they provide an

elegant, yet easy-to-use solution to the problems of the AWT. More than anything else, it is these

two features that define the essence of Swing.

Some of the Swing Components And Examples:

JLabel:

With the JLabel class, one can display unselectable text and images. To create a component that

displays a string, an image, or both, one can do so by using or extending JLabel.

Creating and Setting or Getting the Label's Contents

Method or Constructor Purpose

JLabel(Icon)

JLabel(String)

JLabel(String, Icon, int)

JLabel()

Creates a JLabel instance, initializing it to have the specified

text/image/alignment. The int argument specifies the horizontal

alignment of the label's contents within its drawing area. The

horizontal alignment must be one of the following constants

defined in the SwingConstants interface (which JLabel

implements): LEFT, CENTER, RIGHT, LEADING, or

TRAILING.

void setText(String)

String getText()

Sets or gets the text displayed by the label. HTML tags can be

used to format the text.

void setIcon(Icon)

Icon getIcon() Sets or gets the image displayed by the label.

JPanel:

The JPanel is a general-purpose container for lightweight components. By default, panels do not

add colors to anything except their own background; however, one can easily add borders to

them and otherwise customize their painting.

Creating a JPanel

Constructor Purpose

JPanel()

JPanel(LayoutManager)

Creates a panel. The LayoutManager parameter provides a

layout manager for the new panel. By default, a panel uses a

FlowLayout to lay out its components.

Managing a Container's Components

Method Purpose

void add(Component)

void add(Component, int)

Adds the specified component to the panel. When present, the

int parameter is the index of the component within the

container. By default, the first component added is at index 0,

int getComponentCount() Gets the number of components in this panel.

Setting or Getting the Layout Manager

Method Purpose

void

setLayout(LayoutManager)

LayoutManager getLayout()

Sets or gets the layout manager for this panel. The layout

manager is responsible for positioning the panel's components

within the panel's bounds according to some philosophy.

JTextField:

JTextField allows editing/displaying of a single line of text. New features include the ability to

justify the text left, right, or center, and to set the text’s font. When the user types data into them

and presses the Enter key, an action event occurs. If the program registers an event listener, the

listener processes the event and can use the data in the text field at the time of the event in the

program. JTextField is an input area where the user can type in characters.

Creating and Setting or Obtaining the Field's Contents

Method or Constructor Purpose

JTextField()

JTextField(String)

JTextField(String, int)

JTextField(int)

Creates a text field. When present, the int argument specifies

the desired width in columns. The String argument contains the

field's initial text.

void setText(String)

String getText() Sets or obtains the text displayed by the text field.

Fine Tuning the Field's Appearance

Method Purpose

void setEditable(boolean)

boolean isEditable()

(defined in JTextComponent)

Sets or indicates whether the user can edit the text in the text

field.

Implementing the Field's Functionality

Method Purpose

void addActionListener(ActionListener)

void removeActionListener(ActionListener) Adds or removes an action listener.

JTextArea:

JTextArea allows editing of multiple lines of text. JTextArea can be used in conjunction with

class JScrollPane to achieve scrolling. The underlying JScrollPane can be forced to always or

never have either the vertical or horizontal scrollbar.

Creating and Setting or Obtaining Contents

Method or Constructor Purpose

JTextArea()

JTextArea(String)

JTextArea(String, int, int)

JTextArea(int, int)

Creates a text area. When present, the String argument contains

the initial text. The int arguments specify the desired width in

columns and height in rows, respectively.

void setText(String)

String getText() Sets or obtains the text displayed by the text area.

Fine Tuning the Text Area's Appearance

Method Purpose

void setEditable(boolean)

boolean isEditable()

Sets or indicates whether the user can edit the text in the text

area.

void setColumns(int);

int getColumns()

Sets or obtains the number of columns displayed by the text area.

This is really just a hint for computing the area's preferred width.

void setRows(int);

int getRows()

Sets or obtains the number of rows displayed by the text area.

This is a hint for computing the area's preferred height.

JComboBox:

A JComboBox, which lets the user choose one of several choices, can have two very different

forms. The default form is the uneditable combo box, which features a button and a drop-down

list of values. The second form, called the editable combo box, features a text field with a small

button abutting it. The user can type a value in the text field or click the button to display a drop-

down list.

Creating and Setting or Getting the Items in the Combo Boxes's Menu

Method Purpose

JComboBox()

JComboBox(Object[])

JComboBox(Vector)

Create a combo box with the specified items in its menu. A combo box

created with the default constructor has no items in the menu initially.

Each of the other constructors initializes the menu from its argument: a

model object, an array of objects, or a Vector of objects.

void addItem(Object)

void

insertItemAt(Object,

int)

Add or insert the specified object into the combo box's menu. The insert

method places the specified object at the specified index, thus inserting

it before the object currently at that index. These methods require that

the combo box's data model be an instance of

MutableComboBoxModel.

Object getItemAt(int)

Object

getSelectedItem()

Get an item from the combo box's menu.

int getSelectedIndex() Get the index of the selected item in the combo box's menu.

Customizing the Combo Box's Operation

Method or Constructor Purpose

void

addActionListener(ActionListener)

Add an action listener to the combo box. The listener's

actionPerformed method is called when the user selects an

item from the combo box's menu or, in an editable combo

box, when the user presses Enter.

void addItemListener(ItemListener)

Add an item listener to the combo box. The listener's

itemStateChanged method is called when the selection state

of any of the combo box's items change.

void setEditable(boolean)

boolean isEditable() Set or get whether the user can type in the combo box.

JTree:

With the JTree class, you can display hierarchical data. A JTree object does not actually contain

data; it simply provides a view of the data. Like any non-trivial Swing component, the tree gets

data by querying its data model. Here is a picture of a tree:

As the preceding figure shows, JTree displays its data vertically. Each row displayed by the tree

contains exactly one item of data, which is called a node. Every tree has a root node from which

all nodes descend. By default, the tree displays the root node, but you can decree otherwise. A

node can either have children or not. We refer to nodes that can have children — whether or not

they currently have children — as branch nodes. Nodes that can not have children are leaf nodes.

Creating and Setting Up a Tree

Constructor or Method Purpose

JTree()

JTree(TreeNode)

JTree(Object[])

JTree(Vector)

Create a tree. The TreeNode argument specifies the root node, to be

managed by the default tree model. The TreeModel argument

specifies the model that provides the data to the table. The no-

argument version of this constructor is for use in builders; it creates a

tree that contains some sample data. If you specify a Hashtable, array

of objects, or Vector as an argument, then the argument is treated as a

list of nodes under the root node.

void

setEditable(boolean)

The method sets whether the user can edit tree nodes. By default, tree

nodes are not editable.

void

setRootVisible(boolean)

Set whether the tree shows the root node.

Implementing Selection

Method Purpose

void

addTreeSelectionListener(TreeSelectionListener)

Register a listener to detect when the a node

is selected or deselected.

void setSelectionModel(TreeSelectionModel)

TreeSelectionModel getSelectionModel()

Set or get the model used to control node

selections. You can turn off node selection

completely using setSelectionModel(null).

Object getLastSelectedPathComponent()

Get the object representing the currently

selected node. This is equivalent to invoking

getLastPathComponent on the value returned

by tree.getSelectionPath().

void setSelectionPath(TreePath)

TreePath getSelectionPath()

Set or get the path to the currently selected

node.

JTable:

With the JTable class you can display tables of data, optionally allowing the user to edit the data.

JTable does not contain or cache data; it is simply a view of your data. Here is a picture of a

typical table displayed within a scroll pane:

Creating and Setting Up a JTable

Constructor or Method Purpose

JTable() Create a JTable. data is a two-dimensional array of the information

JTable(int numRows, int numColumns)

JTable(Object[][] data, Object[] colHeads)

to be presented, and colHeads is a one-dimensional array with the column headings.

void addColumn(String) Add a column to table.

void addRow(String[]) Add A row to Table.

JTabbedPane:

With the JTabbedPane class, you can have several components, such as panels, share the same

space. The user chooses which component to view by selecting the tab corresponding to the

desired component.

To Create Tabbed Panes:

To create a tabbed pane, instantiate JTabbedPane, create the components you wish it to display,

and then add the components to the tabbed pane using the addTab method. The following picture

shows how tabbed panes look like.

Creating and Setting Up a Tabbed Pane

Method or Constructor Purpose

JTabbedPane() Creates a tabbed pane.

addTab(String, Icon,

Component)

addTab(String,

Component)

Adds a new tab to the tabbed pane. The first argument specifies the

text on the tab. The optional icon argument specifies the tab's icon.

The component argument specifies the component that the tabbed

pane should show when the tab is selected.

Inserting, Removing, Finding, and Selecting Tabs

Method Purpose

int getSelectedIndex()

Component getSelectedComponent() Returns the index or component for the selected tab.

JButton:

JButton are very similar to Button. One can create a JButton with a String as a label, and then

drop it in a window. Events are normally handled just as with a Button: you attach an

ActionListener via the addActionListener method.

Setting or Getting the Button's Contents

Method or

Constructor Purpose

JButton(String, Icon)

JButton(String)

JButton(Icon)

JButton()

Create a JButton instance, initializing it to have the specified

text/image/action.

void setText(String)

String getText() Set or get the text displayed by the button.

void setIcon(Icon)

Icon getIcon()

Set or get the image displayed by the button when the button isn't selected

or pressed.

Implementing the Button's Functionality

Method or Constructor Purpose

void setActionCommand(String)

String getActionCommand()

Set or get the name of the action performed by the

button.

void

addActionListener(ActionListener)

Add or remove an object that listens for action events

fired by the button.

ActionListener

removeActionListener()

void addItemListener(ItemListener)

ItemListener removeItemListener()

Add or remove an object that listens for item events fired

by the button.

JCheckBox:

A javax.swing.JCheckBox shows a small box that is either marked or unmarked. When you click

on it, it changes from checked to unchecked or vice versa automatically. You don't have to do

any programming for the checkbox to change.

There are two ways to use a checkbox:

1. Active. Use addActionListeneror addItemListener() so that a method will be called

whenever the checkbox is changed.

2. Passive. Use isSelected() to test if a checkbox is checked.

Check Box Constructors

Constructor Purpose

JCheckBox(String)

JCheckBox(String,

boolean)

JCheckBox()

Create a JCheckBox instance. The string argument specifies the text, if

any, that the check box should display. Specifying the boolean argument

as true initializes the check box to be selected. If the boolean argument is

absent or false, then the check box is initially unselected.

JRadioButton:

JRadioButton is similar to JCheckbox, except for the default icon for each class. A set of radio

buttons can be associated as a group in which only one button at a time can be selected.

Radio Button Constructors

Constructor Purpose

JRadioButton(String)

JRadioButton(String,

boolean)

JRadioButton()

Create a JRadioButton instance. The string argument specifies the text,

if any, that the radio button should display. Specifying the boolean

argument as true initializes the radio button to be selected, subject to the

approval of the ButtonGroup object. If the boolean argument is absent or

false, then the radio button is initially unselected.

Commonly Used Button Group Constructors/Methods

Constructor or Method Purpose

ButtonGroup() Create a ButtonGroup instance.

void add(AbstractButton)

void remove(AbstractButton) Add a button to the group, or remove a button from the group.

public ButtonGroup

clearSelection()

Clears the state of selected buttons in the ButtonGroup. None of

the buttons in the ButtonGroup are selected .

//JTreeDemo.java

import javax.swing.*;

import javax.swing.tree.*;

import javax.swing.event.*;

import java.awt.*;

import java.io.*;

class JTreeDemo extends JFrame implements TreeSelectionListener{

DefaultMutableTreeNode root,t;

JTree jt;

JScrollPane jspt;

//JTextField jtf;

JTextArea ta;

JScrollPane jspta;

JTreeDemo(){

//jtf=new JTextField(20);

ta=new JTextArea(20,60);

jspta=new JScrollPane(ta);

add(jspta,"North");

root= new DefaultMutableTreeNode("Example Programs");

t=new DefaultMutableTreeNode("Java");

root.add(t);

t.add(new DefaultMutableTreeNode("SignUpForm1.java"));

t.add(new DefaultMutableTreeNode("JTreeDemo.java"));

root.add(new DefaultMutableTreeNode("C++"));

jt=new JTree(root);

jspt=new JScrollPane(jt);

add(jspt);

jt.addTreeSelectionListener(this);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

}

public void valueChanged(TreeSelectionEvent e) {

DefaultMutableTreeNode node = (DefaultMutableTreeNode)

jt.getLastSelectedPathComponent();

if (!node.isLeaf()) return;

//Object nodeInfo = node.getUserObject();

//jtf.setText(node.toString());

String fn=node.toString();

ta.setText("");

try{

BufferedReader fs=new BufferedReader( new

FileReader(fn));

String ln;

while((ln=fs.readLine())!=null)

ta.append(ln+"\n");

fs.close();

}

catch(FileNotFoundException ex){}

catch(IOException ex){}

}

public static void main(String[] args){

new JTreeDemo();

}

}

//JTableDemo.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import javax.swing.table.*;

import javax.swing.border.*;

public class JTableDemo extends JFrame {

private DefaultTableModel model;

private JTable table;

public JTableDemo() {

super("Dept");

model = new DefaultTableModel();

model.addColumn("Dept No");

model.addColumn("Dept Name");

model.addColumn("Loc");

String[] cse = { "100", "CSE", "BEC" };

model.addRow(cse);

String[] ece = { "200", "ECE", "BEC" };

model.addRow(ece);

String[] it = { "300", "IT", "BEC" };

model.addRow(it);

table = new JTable(model);

Icon addIcon = new ImageIcon("toolbar-icons/gif/add1.gif");

JButton addButton = new JButton("Add",addIcon);

addButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

String[] dept = { "", "", "" };

model.addRow(dept);

}

});

JButton removeButton = new JButton("Remove Selected Dept");

removeButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent event) {

model.removeRow(table.getSelectedRow());

}

});

JPanel inputPanel = new JPanel();

TitledBorder title;

title = BorderFactory.createTitledBorder("Add/Remove");

inputPanel.setBorder(title);

inputPanel.add(addButton);

inputPanel.add(removeButton);

add(new JScrollPane(table), BorderLayout.CENTER);

add(inputPanel, BorderLayout.NORTH);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setSize(400, 300);

setVisible(true);

}

public static void main(String args[]) {

new JTableDemo();

}

}

// BrowsePanel.java

import javax.swing.*;

import java.awt.event.*;

import java.sql.*;

class BrowsePanel extends JPanel implements ActionListener{

JLabel ql,rl;

JTextField qtf;

JTextArea jta;

JButton exb;

JScrollPane jsp;

Connection con;

Statement stmt;

BrowsePanel(){

setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));

ql=new JLabel("Query");

rl=new JLabel("Results");

qtf=new JTextField(20);

jta=new JTextArea(10,20);

exb=new JButton("Execute");

jsp=new JScrollPane(jta);

jsp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_

ALWAYS);

jsp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_

ALWAYS);

add(ql);

add(qtf);

add(rl);

add(jsp);

add(exb);

//pack();

//setVisible(true);

exb.addActionListener(this);

//Establish JDBC statement

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:mt104";

con=DriverManager.getConnection(url,"scott","tiger");

stmt=con.createStatement();

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

public void actionPerformed(ActionEvent e){

String query=qtf.getText();

try{

ResultSet rset=stmt.executeQuery(query);

jta.setText("");

while(rset.next()){

for(int i=1;i<=rset.getMetaData().getColumnCount();i++)

jta.append(rset.getString(i)+" ");

jta.append("\n");

}

rset.close();

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

}

//DeletePanel.java

class DeletePanel extends JPanel implements ActionListener{

JLabel tnl,knl,kvl;

JTextField tntf,kntf,kvtf;

JButton delb;

Connection con;

Statement stmt;

DeletePanel(){

setLayout(new BoxLayout(this,BoxLayout.PAGE_AXIS));

tnl=new JLabel("table name");

knl=new JLabel("key label");

kvl=new JLabel("key value");

tntf=new JTextField(20);

kntf=new JTextField(20);

kvtf=new JTextField(20);

delb=new JButton("Delete");

add(tnl);

add(tntf);

add(knl);

add(kntf);

add(kvl);

add(kvtf);

add(delb);

//pack();

//setVisible(true);

delb.addActionListener(this);

//Establish JDBC statement

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

String url="jdbc:odbc:mt104";

con=DriverManager.getConnection(url, "scott","tiger");

stmt=con.createStatement();

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

public void actionPerformed(ActionEvent e){

String tn=tntf.getText();

String kn=kntf.getText();

String kv=kvtf.getText();

String query="delete from "+tn+" where "+kn+"="+kv;

try{

stmt.executeUpdate(query);

}catch(Exception ex){

System.out.println(ex.getMessage());

}

}

}

class JTabbedPaneDemo extends JFrame{

JTabbedPane jtb;

BrowsePanel bp1;

DeletePanel dp1;

JTabbedPaneDemo(){

bp1=new BrowsePanel();

dp1=new DeletePanel();

jtb=new JTabbedPane();

jtb.addTab("Browse",bp1);

jtb.addTab("Delete",dp1);

add(jtb);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

setLocation(250,100);

}

public static void main(String[] args){

new JTabbedPaneDemo();

}

}

//SwingTempConverter.java

import javax.swing.*;

import javax.swing.tree.*;

import java.awt.*;

import java.awt.event.*;

class SwingTempConverter extends JFrame{

JLabel cl,fl;

JTextField ct,ft;

JButton cb,clb;

JTree t;

SwingTempConverter(){

JPanel p1=new JPanel();

add(p1);

p1.setLayout(new BoxLayout(p1,BoxLayout.PAGE_AXIS));

JPanel p2=new JPanel();

p2.setLayout(new BoxLayout(p2,BoxLayout.LINE_AXIS));

cl=new JLabel("Celcius");

ct=new JTextField(20);

p2.add(cl);

p2.add(ct);

p2.setBorder(BorderFactory.createTitledBorder("Enter Temperature"));

p1.add(p2);

JPanel p3=new JPanel();

p3.setLayout(new BoxLayout(p3,BoxLayout.LINE_AXIS));

cb=new JButton("Convert");

cb.setToolTipText("Converts Celcius to Fharenheit");

clb=new JButton("Clear");

p3.add(Box.createHorizontalGlue());

p3.add(cb);

p3.add(Box.createHorizontalGlue());

p3.add(clb);

p3.add(Box.createHorizontalGlue());

p3.setBorder(BorderFactory.createTitledBorder("Press a Button"));

p1.add(p3);

JPanel p4=new JPanel();

p4.setLayout(new BoxLayout(p4,BoxLayout.LINE_AXIS));

fl=new JLabel("Fahrenheit");

ft=new JTextField(20);

p4.add(fl);

p4.add(ft);

p4.setBorder(BorderFactory.createTitledBorder("Result"));

p1.add(p4);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

pack();

setVisible(true);

}

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new SwingTempConverter();

}

});

}

}

//JComboBoxDemo.java

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

class JComboBoxDemo extends JFrame implements ActionListener{

JLabel l1,l2;

JTextField jtf;

JButton sb,cb;

JPanel np,bp,bup;

JComboBox bcob;

String branches[]={"CSE","IT","EEE","ECE","MECH"};

String name,branch;

JComboBoxDemo(String s){

super(s);

np=new JPanel();

bp=new JPanel();

bup=new JPanel();

l1=new JLabel("NAME:");

np.add(l1);

jtf=new JTextField(20);

np.add(jtf);

add(np,BorderLayout.NORTH);

l2=new JLabel("Choose Branch:");

bp.add(l2);

bcob=new JComboBox(branches);

bp.add(bcob);

add(bp);

sb=new JButton("SUBMIT");

cb=new JButton("CLEAR");

bup.add(sb);

bup.add(cb);

add(bup,BorderLayout.SOUTH);

sb.addActionListener(this);

cb.addActionListener(this);

bcob.addActionListener(this);

setDefaultCloseOperation(EXIT_ON_CLOSE);

pack();

//setSize(400, 300);

setVisible(true);

}

public void actionPerformed(ActionEvent e){

if(e.getSource()==bcob)

branch=branches[bcob.getSelectedIndex()];

if(e.getActionCommand().equals("SUBMIT"))

displayDetails();

else if(e.getSource()==cb){

jtf.setText("");

bcob.setSelectedIndex(0);

}

}

void displayDetails(){

name=jtf.getText();

String details="";

details=name+"\n"+branch;

JOptionPane.showMessageDialog(this,details,"ComboBox",JOptionPane.PLAIN

_MESSAGE);

}

public static void main(String []args){

new JComboBoxDemo("JComboBox");

}

}