Sunteți pe pagina 1din 15

import java.awt.

*;
import java.awt.event.*;
class AEvent extends Frame implements
ActionListener{
TextField tf1,tf2; Label l1;
AEvent(){

//create components
setTitle("Adder");
tf1=new TextField();
tf2=new TextField();
tf1.setBounds(60,50,170,20);
tf2.setBounds(60,100,170,20);
Button b=new Button("click me");
b.setBounds(100,140,80,30);
l1=new Label("");
l1.setBounds(60,200,100,100);
//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf1); add(tf2);add(l1);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
int c = a + b;
//System.out.println(String.valueOf(c));
l1.setText("Their sum is = " + c);

}
public static void main(String args[]){
new AEvent();
}
}
Java 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.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT provides less components than Swing. Swing provides more powerful
components such as tables, lists,
scrollpanes, colorchooser, tabbedpane etc.

4) AWT doesn't follows MVC(Model View Controller) where Swing follows MVC.
model represents data, view represents presentation and
controller acts as an interface between model and view.
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of desktop
applications.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.


public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.

Java Swing Examples


There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

1. import javax.swing.*;
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5.
6. JButton b=new JButton("click");//creating instance of JButton
7. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
8.
9. f.add(b);//adding button in JFrame
10.
11. f.setSize(400,500);//400 width and 500 height
12. f.setLayout(null);//using no layout managers
13. f.setVisible(true);//making the frame visible
14. }
15. }
Simple example of Swing by inheritance

1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7.
8. add(b);//adding button on frame
9. setSize(400,500);
10. setLayout(null);
11. setVisible(true);
12. }
13. public static void main(String[] args) {
14. new Simple2();
15. }}
Java JList
The class JList is a component which displays a list of objects and allows the user to select
one or more items. A separate model, ListModel, maintains the contents of the list.

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.

If you want to present a set of choices to a user, and a radio button or checkbox set consumes too
much space, you can use a combo box or a list.

JList class declaration

Let's see the declaration for javax.swing.JList class.

public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:


Constructor Description

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the specified array.

Commonly used Methods:


Methods Description

Void It is used to add a listener to the


addListSelectionListener(ListSelectionListener list, to be notified each time a
listener) change to the selection occurs.

int getSelectedIndex() It is used to return the smallest


selected cell index.
ListModel getModel() It is used to return the data model
that holds a list of items displayed
by the JList component.

void setListData(Object[] listData) It is used to create a read-only


ListModel from an array of objects.

Most Swing components have models. A button (JButton), for example, has a model (a ButtonModel object) that stores
the button's state — what its keyboard mnemonic is, whether it's enabled, selected, or pressed, and so on. Some
components have multiple models. A list (JList), for example, uses a ListModel to hold the list's contents, and
a ListSelectionModel to track the list's current selection.

how data is stored and retrieved.

DefaultListModel Class

Package: javax.swing

DefaultListModel provides a simple implementation of a list model, which can be used to manage
items displayed by a JList control.

Constructor

Constructor Description

DefaultListModel() Creates a new list model object

Methods
Method Description

void add(Object element, int


Adds an element at the specified position
index)

void addElement(Object
Adds an element to the end of the list
element))

void clear() Removes all elements from the list

boolean Contains(Object Returns true if the specified element is in


element) the list

Object firstElement() Returns the first element in the list

Object get(int index) Returns the element at the specified location

boolean isEmpty() Returns true if the list is empty

Object lastElement() Returns the last element in the list

Removes the element from the specified


void remove(int index)
position in the list

void removeElement (Object


Removes the specified element from the list
element)

int size() Returns the number of elements in the list

Returns an array containing each element in


Object[] toArray()
the list
Java JList Example
1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}
Java JList Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ListExample
4. {
5. ListExample(){
6. JFrame f= new JFrame();
7. final JLabel label = new JLabel();
8. label.setSize(500,100);
9. JButton b=new JButton("Show");
10. b.setBounds(200,150,80,30);
11. final DefaultListModel<String> l1 = new DefaultListModel<>();
12. l1.addElement("C");
13. l1.addElement("C++");
14. l1.addElement("Java");
15. l1.addElement("PHP");
16. final JList<String> list1 = new JList<>(l1);
17. list1.setBounds(100,100, 75,75);
18. DefaultListModel<String> l2 = new DefaultListModel<>();
19. l2.addElement("Turbo C++");
20. l2.addElement("Struts");
21. l2.addElement("Spring");
22. l2.addElement("YII");
23. final JList<String> list2 = new JList<>(l2);
24. list2.setBounds(100,200, 75,75);
25. f.add(list1); f.add(list2); f.add(b); f.add(label);
26. f.setSize(450,450);
27. f.setLayout(null);
28. f.setVisible(true);
29. b.addActionListener(new ActionListener() {
30. public void actionPerformed(ActionEvent e) {
31. String data = "";
32. if (list1.getSelectedIndex() != -1) {
33. data = "Programming language Selected: " + list1.getSelectedValue();
34. label.setText(data);
35. }
36. if(list2.getSelectedIndex() != -1){
37. data += ", FrameWork Selected: ";
38. for(Object frame :list2.getSelectedValues()){
39. data += frame + " ";
40. }
41. }
42. label.setText(data);
43. }
44. });
45. }
46. public static void main(String args[])
47. {
48. new ListExample();
49. }}

The Model-View-Controller Architecture


Swing uses the model-view-controller architecture (MVC) as the fundamental design behind each of its
components. Essentially, MVC breaks GUI components into three elements. Each of these elements plays a
crucial role in how the component behaves.

Model

The model encompasses the state data for each component. There are different models for different
types of components. For example, the model of a scrollbar component might contain information
about the current position of its adjustable “thumb,” its minimum and maximum values, and the
thumb’s width (relative to the range of values). A menu, on the other hand, may simply contain a list
of the menu items the user can select from. Note that this information remains the same no matter how
the component is painted on the screen; model data always exists independent of the component’s
visual representation.

View

The view refers to how you see the component on the screen. For a good example of how views can
differ, look at an application window on two different GUI platforms. Almost all window frames will
have a titlebar spanning the top of the window. However, the titlebar may have a close box on the left
side (like the older MacOS platform), or it may have the close box on the right side (as in the
Windows 95 platform). These are examples of different types of views for the same window object.

Controller

The controller is the portion of the user interface that dictates how the component interacts with
events. Events come in many forms — a mouse click, gaining or losing focus, a keyboard event that
triggers a specific menu command, or even a directive to repaint part of the screen. The controller
decides how each component will react to the event—if it reacts at all.

Figure 1.5 shows how the model, view, and controller work together to create a scrollbar component. The
scrollbar uses the information in the model to determine how far into the scrollbar to render the thumb and how
wide the thumb should be. Note that the model specifies this information relative to the minimum and the
maximum. It does not give the position or width of the thumb in screen pixels—the view calculates that. The
view determines exactly where and how to draw the scrollbar, given the proportions offered by the model. The
view knows whether it is a horizontal or vertical scrollbar, and it knows exactly how to shadow the end buttons
and the thumb. Finally, the controller is responsible for handling mouse events on the component. The
controller knows, for example, that dragging the thumb is a legitimate action for a scroll bar, and pushing on
the end buttons is acceptable as well. The result is a fully functional MVC scrollbar.

Figure 1-5. The three elements of a model-view-controller architecture


MVC Interaction

With MVC, each of the three elements—the model, the view, and the controller—requires the services of
another element to keep itself continually updated. Let’s continue discussing the scrollbar component.

We already know that the view cannot render the scrollbar correctly without obtaining information from the
model first. In this case, the scrollbar will not know where to draw its “thumb” unless it can obtain its current
position and width relative to the minimum and maximum. Likewise, the view determines if the component is
the recipient of user events, such as mouse clicks. (For example, the view knows the exact width of the thumb;
it can tell whether a click occurred over the thumb or just outside of it.) The view passes these events on to the
controller, which decides how to handle them best. Based on the controller’s decisions, the values in the model
may need to be altered. If the user drags the scrollbar thumb, the controller will react by incrementing the
thumb’s position in the model. At that point, the whole cycle can repeat. The three elements, therefore,
communicate their data as shown in Chapter 11.

Figure 1-6. Communication through the model-view-controller architecture

MVC in Swing

Swing actually makes use of a simplified variant of the MVC design called the model-delegate . This design
combines the view and the controller object into a single element that draws the component to the screen and
handles GUI events known as the UI delegate . Bundling graphics capabilities and event handling is somewhat
easy in Java, since much of the event handling is taken care of in AWT. As you might expect, the
communication between the model and the UI delegate then becomes a two-way street, as shown in Figure 1.7.
Figure 1-7. With Swing, the view and the controller are combined into a UI-delegate object

So let’s review: each Swing component contains a model and a UI delegate. The model is responsible for
maintaining information about the component’s state. The UI delegate is responsible for maintaining
information about how to draw the component on the screen. In addition, the UI delegate (in conjunction with
AWT) reacts to various events that propagate through the component.

Note that the separation of the model and the UI delegate in the MVC design is extremely advantageous. One
unique aspect of the MVC architecture is the ability to tie multiple views to a single model. For example, if
you want to display the same data in a pie chart and in a table, you can base the views of two components on a
single data model. That way, if the data needs to be changed, you can do so in only one place—the views
update themselves accordingly (Chapter 16, has an example that does exactly this). In the same manner,
separating the delegate from the model gives the user the added benefit of choosing what a component will
look like without affecting any of its data. By using this approach, in conjunction with the lightweight design,
Swing can provide each component with its own pluggable look-and-feel.

S-ar putea să vă placă și