Object Oriented programming. Java. Oracle JDeveloper. Обработка событий. Графический интерфейс пользователя. Менеджер размещения GridBagLayout

Страницы работы

64 страницы (Word-файл)

Фрагмент текста работы

Object Oriented programming. Java. Oracle JDeveloper

Lectures 4-5

B. Обработка событий. Графический интерфейс пользователя.

Event Handling and User Interface Components

Event Handling

An operating environment that supports GUI monitors the following events:

·  Button click

·  Window events

·  Keyboard events

·  Focus events

·  Mouse events

·  Consuming events

The event handling procedure is based on objects of 3 types.

Event source objects- buttons, scroll bars etc. So it is an object that can register listener objects and send them event objects.

Event object. The information about the event is encapsulated in an event object. In Java, all event objects ultimately derive from the class java.util.EventObject. There are subclasses for each event type, such as ActionEvent and WindowEvent.

Event listener objects – objects that carry out the desired response to the event. A listener object implements a special interface called a listener interface.

How it works:

The event source sends out event objects to all registered listeners when the event occurs.

The listener objects will then use the information in the event object to determine their reaction to the event.

You register the listener object with the source object by using an instruction like this:

EventSourceObject.addEventListener(eventListenerObject);


Handling a button click

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{

public static void main(String[] args)

{new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{

public SimpleFrame()

{super("This is my frame!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel buttonPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(buttonPanel);

setSize (300,150);

setVisible(true);

}

}

class MyPanel extends JPanel

{

public MyPanel()

{ // creates labels and buttons

JLabel myText = new JLabel("This is my text");

JButton button1 = new JButton("Button 1");

JButton button2 = new JButton("Button 2");

// add label and buttons to panel

add(button1);

add(button2);

add(myText);

// create button actions

MyAction first = new MyAction(Color.yellow);

MyAction second = new MyAction(Color.blue);

// associate actions with buttons

button1.addActionListener(first);

button2.addActionListener(second);

}

// description of the action listeners reactions

private class MyAction implements ActionListener

{

public MyAction(Color c)

{ backgrColor=c;}

public void actionPerformed (ActionEvent event)

{setBackground(backgrColor);

//  repaint();

}

private Color backgrColor;

}

}

This program draws 2 buttons. You click a button and change the background color.

JButton button1 = new JButton("Button 1");

MyAction  first  = new MyAction(Color.yellow);

button1.addActionListener(first);

After it the listener object first is notified whenever an “action event” occurs in the button. (A button click is an action event for buttons.)

You see, the listener objects implement the ActionListener interface. To implement the ActionListener interface, the listener class must realise a method called actionPerformed that receives an ActionEvent object as a parameter.

In this program there are two listener objects: first and second.

User clicks button1 or button2. The clicked button creates an ActionEvent object and calls first.actionPerfomed(event) or second.actionPerfomed(event) correspondingly, passing that event object. So the associated listener object (here: either first or second) receives an action event that indicates a button click. And provides a response.


Here clicking a button you also change the text

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{

public static void main(String[] args)

{new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{

public SimpleFrame()

{super("This is my frame!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel buttonPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(buttonPanel);

setSize (300,150);

setVisible(true);

}

}

class MyPanel extends JPanel

{

public MyPanel()

{

JLabel myText = new JLabel("This is my text");

JButton button1 = new JButton("Yellow");

JButton button2 = new JButton(" Blue ");

add(button1);

add(button2);

add(myText);

MyAction first = new MyAction(Color.yellow);

MyAction second = new MyAction(Color.blue);

button1.addActionListener(first);

button2.addActionListener(second);

}

public void paintComponent(Graphics g)

{super.paintComponent(g);

g.drawString(text, 30,70);

}

// description of the action listeners reactions

private class MyAction implements ActionListener

{

public MyAction(Color c)

{ backgrColor=c;}

public void actionPerformed (ActionEvent event)

{setBackground(backgrColor);

text="A button was pressed";

// repaint();

}

private Color backgrColor;

}

String text="No button was pressed";

}


No inner class here

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{

public static void main(String[] args)

{new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{

public SimpleFrame()

{super("This is my frame!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel buttonPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(buttonPanel);

setSize (300,150);

setVisible(true);

}

}

class MyPanel extends JPanel implements ActionListener

{

public MyPanel()

{ // creates buttons

button1 = new JButton("Yellow");

button2 = new JButton(" Blue ");

// add buttons to panel

add(button1);

add(button2);

// associate actions with buttons

button1.addActionListener(this);

button2.addActionListener(this);

}

// drawing text in panel

public void paintComponent(Graphics g)

{super.paintComponent(g);

g.drawString(text, 30,70);

}

public void actionPerformed (ActionEvent event)

{Object source=event.getSource();

if (source==button1)

{setBackground(Color.yellow);

text="The first button was pressed";}

else if (source==button2)

{setBackground(Color.blue);

text="The second button was pressed";}

// repaint(); // No need because setBackground() is called here

}

JButton button1, button2;

String text="No button was pressed";

}

In the previous programs we use objects of a new class that was expressly created for carrying out the desired button actions.

We had a special inner private class MyAction in the MyPanel class.

Here is another strategy: add an actionPerformed() method to an existing class.

¬ The panel sets itself as the listener to all two buttons.

Buttons no longer have individual listeners. They share a single listener object. This object is the panel.

¬ Therefore this method must figure out which button was clicked and how to respond.

All the event classes have the EventObject superclass. The EventObject class has the getSource() function. It tells the source of every event.

Conclusion:

To handle button events, each button requires the same treatment:

1.  Construct the button with a label string

2.  Add the button to the panel

3.  Construct an action listener with the appropriate action

4.  Add that action listener to the list of button listeners


Text input components

Text input

In Java two components are used to get text input: text fields and text areas. The classes are called JTextFieldand JTextArea and are described in the javax.swing package.

Both of these classes inherit from a class called JTextComponent.

Here JTextField objects are discussed.

Constructor:

JTextField(String s, int n);

s - the string that would be initially placed inside the field

n – the size of the text field

Other methods of this class:

void setText (String t) changes the text of a text component.

String getText() returns the text contained in this text component

void setEditable(boolean b) determines whether the user can edit the contents.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{ public static void main(String[] args)

{ new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{ public SimpleFrame()

{super("my interactive form!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel testPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(testPanel);

setSize (340,170);

setVisible(true);

}

}

class MyPanel extends JPanel implements ActionListener

{ public MyPanel()

{JLabel lab1= new JLabel("Name:");

JLabel lab2= new JLabel("    Zip:");

text1 = new JTextField("", 10);

text2 = new JTextField("", 8);

button1 = new JButton("Ok");

button2 = new JButton("Clear");

add(lab1);

add(text1);

add(lab2);

add(text2);

add(button1);

add(button2);

button1.addActionListener(this);

button2.addActionListener(this);

}

public void paintComponent(Graphics g)

{super.paintComponent(g);

{ g.drawString("Name: "+ name, 30,80);

g.drawString("Zip: "+ zip, 30,95);

g.drawString(message, 90,120);

}

}

public void actionPerformed (ActionEvent event)

{Object source=event.getSource();

if (source==button1)

{name=text1.getText();

zip=text2.getText();

message="The OK button was pressed";}

else if (source==button2)

{text1.setText("");

text2.setText("");

message="The CLEAR button was pressed";}

repaint();

}

JButton button1, button2;

JTextField text1, text2;

String message="No button was pressed";

String name="", zip="";

}


Text Areas

The example shows how to use a textArea.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{ public static void main(String[] args)

{new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{ public SimpleFrame()

{super("My interactive form!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel testPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(testPanel);

setSize (340,250);

setVisible(true);

}

}

class MyPanel extends JPanel implements ActionListener

{ public MyPanel()

{JLabel lab1= new JLabel("Name:");

JLabel lab2= new JLabel("  Password:");

JLabel lab3= new JLabel("  Address:");

text1 = new JTextField("", 10);

text2 = new JTextField("", 8);

text3 = new JTextArea(4, 20);  // 4 lines of 20 columns each

text3.setLineWrap(true);

button1 = new JButton("Ok");

button2 = new JButton("Clear");

add(lab1);

add(text1);

add(lab2);

add(text2);

add(lab3);

add(text3);

add(button1);

add(button2);

button1.addActionListener(this);

button2.addActionListener(this);

}

public void paintComponent(Graphics g)

{super.paintComponent(g);

g.drawString("Name: "+ name, 30,160);

g.drawString("Psw: "+ psw, 30,180);

g.drawString("Address: "+ address, 30,200);

g.drawString(message, 90,220);

}

public void actionPerformed (ActionEvent event)

{Object source=event.getSource();

if (source==button1)

{name=text1.getText();

psw=text2.getText();

address=text3.getText();

message="The OK button was pressed";}

else if (source==button2)

{text1.setText("");

text2.setText("");

text3.setText("");

message="The CLEAR button was pressed";}

repaint();

}

JButton button1, button2;

JTextField text1, text2;

JTextArea text3;

String message="No button was pressed";

String name="", psw="", address="";

}

Note: a column in a textArea format is a very imprecise measurement, it’s not an upper limit on the number of characters the user can enter.


Better text area and password fields

The example shows how to scroll a textArea and how to use passwordFields.

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class MyProg

{ public static void main(String[] args)

{ new SimpleFrame();

}

}

class SimpleFrame extends JFrame

{ public SimpleFrame()

{super("My interactive form!");

setDefaultCloseOperation(EXIT_ON_CLOSE);

MyPanel testPanel=new MyPanel();

Container contentPane= getContentPane();

contentPane.add(testPanel);

setSize (300,230);

setVisible(true);

}

}

class MyPanel extends JPanel implements ActionListener

{ public MyPanel()

{JLabel lab1= new JLabel("Name:");

JLabel lab2= new JLabel("  Passw:");

JLabel lab3= new JLabel("  Address:");

text1 = new JTextField("", 8);

text2 = new JPasswordField("", 8);

text3 = new JTextArea(3, 6); //3 lines of 6 columns each

JScrollPane scrollPane = new JScrollPane(text3);   // Optional. If you want to scroll the textArea.

text3.setLineWrap(true);

button1 = new JButton("Ok");

button2 = new JButton("Clear");

add(lab1);

add(text1);

add(lab2);

add(text2);

add(lab3);

add(scrollPane);       // If you do not want to scroll the textArea, simply write add(text3);

add(button1);

add(button2);

button1.addActionListener(this);

button2.addActionListener(this);

}

public void paintComponent(Graphics g)

{super.paintComponent(g);

g.drawString("Name: "+ name, 30,160);

g.drawString("Passw: "+ passw, 30,180);

g.drawString("Address: "+ address, 30,200);

g.drawString(message, 90,220);

}

public void actionPerformed (ActionEvent event)

{Object source=event.getSource();

if (source==button1)

{name=text1.getText();

passw=text2.getText();

address=text3.getText();

message="The OK button was pressed";}

else if (source==button2)

{text1.setText("");

text2.setText("");

text3.setText("");

message="The CLEAR button was pressed";}

repaint();

}

JButton button1, button2;

JTextField text1, text2;

JTextArea text3;

String message="No button was pressed";

String name="", passw="", address="";

}


Capturing window events

You may want to handle window events in a non-standard ways. For example, when the user closes the frame, you may want to put up a dialog to warn the user if unsaved work is about to be lost, and only exit program when the user agrees.

When the user tries to do something with a frame window, the JFrame object is the source of a WindowEvent. If you want to catch this event, you must:

1.  Construct an action listener with the appropriate action

2.  Add that action listener to the list of window listeners.

The window listener must be an object of a class that implements the WindowListener interface:

public interface WindowListener

{void windowOpened (WindowEvent e);  // вызывается один раз при открытии окна

void windowClosing (WindowEvent e);  // вызывается при закрытии окна пользователем

// с помощью системного меню.

void windowClosed (WindowEvent e);   // вызывается при закрытии окна вследствии вызова

// метода dispose(), который освобождает ресурсы экрана.

void windowIconified (WindowEvent e);

void windowDeiconified (WindowEvent e);

void windowActivated (WindowEvent e);

void windowDeactivated (WindowEvent e);

}

As always in Java, any class that implements an interface must

Похожие материалы

Информация о работе