Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
JAVA Programming Language
Chapter 6. Windows Programming
Juho Kim
Department of Computer Science and Engineering
Sogang University
6-1
Windows programming
Event-Oriented Programming
– Delegation Event Model
Keyboard Event
Mouse Event
AWT Components - Button
– Checkbox, Checkbox Group: Radio Buttons, Choice, Canvas, TextField,
TextArea, List, Dialog, Scrollbar, Menu, CheckboxMenuItem, Popup Menu,
Printing
6-2
Event-Oriented Programming
– Events : Objects that describes what happened
• When the user performs an action at the user interface level(clicks a
mouse or presses a key), this causes an event to be issued. A
number of different types of event classes exist to describe different
categories of user action.
– Event sources : The generator of an event
• For example, a mouse click on a Button components generates an
ActionEvent with the button as the source. The ActionEvent
instance is an object that contains information about the events that
just took place. It contains:
– getActionCommand() : returns the command name
associated with action
– getModifiers() : returns any modifiers held during the
action
– Event handlers : A method that receives an event object, deciphers it,
and processes the user’s interaction
6-3
Delegation event model
Panel and Frame
event handlers
Frame
Panel
Action event
Action handler
Button
actionPerformed (ActionEvent e) {
…..
}
– Events are sent to the component from which the event originated, but it
is up to each component to propagate the event to one or more
registered classes called listeners. Listeners contain event handlers that
can receive and process the event. In this way, the event handler can be
in an object separate from the component. Listeners are classes that
implement the EventListener interface.
6-4
TestButton.java
import java.awt.*;
public class TestButton {
public static void main(String args[]) {
Frame f = new Frame("Test");
Button b = new Button("Press Me");
b.addActionListener(new ButtonHandler());
f.add(b,BorderLayout.CENTER);
f.pack();
f.setVisible(true);
}
}
import java.awt.event.*;
public class ButtonHandler implements
ActionListener {
public void actionPerformed(ActionEvent e)
{
System.out.println("Action occurred");
System.out.println("Button's label is :”
+ e.getActionCommand());
}
}
TestButton.java
ButtonHandler.java
6-5
– The Button class has an addActionListerner method - ActionListener
– The ActionListener interface defines a single method, actionPerformed,
which receives an ActionEvent
– When a Button object is created, it can have an object registered as a
listener for ActionEvents through the addActionListener() method.
The registered listener is instantiated from a class that implements the
ActionListener interface.
– When the Button object is clicked on with the mouse, and ActionEvent is
sent. The ActionEvent is received through the actionPerformed() method
of any ActionListener that is registered on the button through its
addActionListener() method.
– The method getActionCommand() of the ActionEvent class returns the
command name associated with this action.
6-6
Event Hierarchy
ActionEvent
ContainerEvent
Adjustment Event
FocusEvent
java.awt.event
ComponentEvent
KeyEvent
InputEvent
ItemEvent
MouseEvent
WindowEvent
TextEvent
6-7
Method Categories and Interfaces
Category
Action
Item
Mouse motion
Interface Name
ActionListener
ItemListener
MouseMotionListener
Mouse button
MouseListener
Key
KeyListener
Focus
FocusListener
Adjustment
AdjustmentListener
6-8
Methods
actionPerformed(ActionEvent)
itemStateChanged(ItemEvent)
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mouseClicked(MouseEvent)
keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
focusGained(FocusEvent)
focusLost(FocusEvent)
adjustmentValueChanged
(AdjustmentEvent)
Method Categories and Interfaces
Category
Interface Name
Methods
Window
WindowListener
Component
ComponentListener
Container
ContainerListener
Text
TextListener
windowClosing(WindowEvent)
windowOpened(WindowEvent)
windowIconified(WindowEvent)
windowDeiconified(WindowEvent)
windowClosed(WindowEvent)
windowActivated(WindowEvent)
windowDeactivated(WindowEvent)
componentMoved(ComponentEvent)
componentHidden(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
componentAdded(ContainerEvent)
componentRemoved(ContainerEvent)
textValueChanged(TextEvent)
6-9
Keyboard event methods
6-10
evKbd.java
import java.awt.*;
import java.awt.event.*;
public class evKbd implements KeyListener
{
private Frame f;
public evKbd()
{
f = new Frame("KeyEvent Test");
f.setBackground(Color.white);
f.addKeyListener(this);
f.setSize(200,200);
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
}
6-11
evKbd.java
public void keyTyped(KeyEvent e) {
Graphics g = f.getGraphics();
g.setFont(new Font("바탕체", Font.PLAIN, 20));
g.clearRect(0,0, 200,200);
// delete privious printed value
g.drawString("키
: " + e.getKeyChar(), 30,100);
g.drawString("키코드 : " + (int) e.getKeyChar(), 30,130);
}
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
//--------------------------------------------------------------------public static void main(String[] args)
{
evKbd mf = new evKbd(); // frame construction
}
}
6-12
Special Keys
"Key typed" events
– are higher-level and generally do not depend on the platform or
keyboard layout. They are generated when a character is entered, and
are the preferred way to find out about character input. In the simplest
case, a key typed event is produced by a single key press (e.g., 'a').
"Key pressed" and "key released" events
– are lower-level and depend on the platform and keyboard layout. They
are generated whenever a key is pressed or released, and are the only
way to find out about keys that don't generate character input (e.g.,
action keys, modifier keys, etc.). The key being pressed or released is
indicated by the getKeyCode method, which returns a virtual key code.
Virtual key codes
– are used to report which keyboard key has been pressed, rather than a
character generated by the combination of one or more keystrokes (like
"A", which comes from shift and "a"). For example, pressing the Shift
key will cause a KEY_PRESSED event with a VK_SHIFT keyCode, while
pressing the 'a' key will result in a VK_A keyCode. After the 'a' key is
released, a KEY_RELEASED event will be fired with VK_A. Separately, a
KEY_TYPED event with a keyChar value of 'A' is generated.
6-13
evTukSuKey.java
import java.awt.*;
import java.awt.event.*;
public class evTukSuKey implements
KeyListener
{ private Frame f;
private int x=250,y=150;
public evTukSuKey ()
{
f = new Frame("KeyEvent Test");
f.setBackground(Color.white);
f.addKeyListener(this);
f.setSize(200,200);
WindowDestroyer listener =
new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true); }
public void keyPressed(KeyEvent e)
{
int l=10;
char c = e.getKeyChar();
int keyCode = e.getKeyCode();
int modifiers = e.getModifiers();
Graphics g = f.getGraphics();
if (keyCode == 16) // VK_SHIFT
l +=10;
if (keyCode == 17) // VK_CONTROL
l +=20;
switch (keyCode)
{ case 38 : y -= l; break; // VK_UP
case 40 : y += l; break;// VK_DOWN
case 37 : x -= l; break; // VK_LEFT
case 39 : x += l; break; // VK_RIGHT
case 35 : System.exit(0);
}
g.fillOval(x, y, l,l); // draw oval
}
public void keyTyped(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }
public static void main(String[] args)
{ evTukSuKey mf = new evTukSuKey ();
}}
6-14
Mouse event
public abstract class MouseAdapter extends Object implements
MouseListener
– An abstract adapter class for receiving mouse events. The methods in
this class are empty. This class exists as convenience for creating listener
objects.
– Mouse events let you track when a mouse is pressed, released, clicked,
when it enters a component, and when it exits. (To track mouse moves
and mouse drags, use the MouseMotionAdapter.)
– Extend this class to create a MouseEvent listener and override the
methods for the events of interest. (If you implement the MouseListener
interface, you have to define all of the methods in it. This abstract class
defines null methods for them all, so you can only have to define
methods for events you care about.)
– Create a listener object using the extended class and then register it with
a component using the component's addMouseListener method. When a
mouse button is pressed, released, or clicked (pressed and released), or
when the mouse cursor enters or exits the component, the relevant
method in the listener object is invoked and the MouseEvent is passed to
it.
6-15
MouseListener
6-16
MouseMotionListener
public abstract class MouseMotionAdapter extends
Object implements MouseMotionListener
– Mouse motion events occur when a mouse is moved or dragged. (Many
such events will be generated in a normal program. To track clicks and
other mouse events, use the MouseAdapter.)
6-17
Multiple listeners
– The AWT event listening framework allows multiple listeners to be
attached to the same component.
– The listener mechanism allows you to call an addXXXListener() method
as many times as needed, and you can specify as many different
listeners as your design requires. All registered listeners have their
handler methods called when the event occurs.
– In the next example,
f.addMouseListener(this);
f.addMouseMotionListener(this);
both types of events cause methods to be called in the TwoListen class.
6-18
TwoListen.java
import java.awt.*;
import java.awt.event.*;
public class TwoListen implements MouseMotionListener, MouseListener {
private TextField tf;
private Frame f;
public TwoListen () {
f = new Frame("Two mouse listeners example");
f.add(new Label ("Click and drag the mouse"),
BorderLayout.NORTH);
tf = new TextField(30);
f.add(tf, BorderLayout.SOUTH);
f.addMouseMotionListener(this);
f.addMouseListener(this);
f.setSize(300,200);
WindowDestroyer listener = new WindowDestroyer(); // window destroy button
f.addWindowListener(listener);
f.setVisible(true);
}
6-19
TwoListen.java
public void mouseDragged(MouseEvent e) {
String s = "Mouse dragging: X = " + e.getX() +
" Y = " + e.getY();
tf.setText(s);
}
public void mouseEntered(MouseEvent e) {
String s = "The mouse Entered";
tf.setText(s); }
public void mouseExited(MouseEvent e) {
String s = "The mouse has left the building";
tf.setText(s);
}
public void mouseMoved(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public static void main(String args[]) {
TwoListen two = new TwoListen();
} }
6-20
AWT Components
–
–
–
–
–
–
–
–
–
–
–
–
–
–
Button
Checkbox
Checkbox Group: Radio Buttons
Choice
Canvas
TextField
TextArea
List
Dialog
ScrollPane
Menu
CheckboxMenuItem
Popup Menu
Printing
6-21
ButtonDemo.java
import java.awt.*;
import java.awt.event.*;
public class ButtonDemo implements ActionListener {
private Frame f;
public ButtonDemo () {
f = new Frame("Button Example");
Button b = new Button("sample");
b.addActionListener(this);
f.add(b);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
System.out.println("Button press received.");
System.out.println("Button's action command is: " + e.getActionCommand());
}
public static void main(String args[]) {
ButtonDemo bd = new ButtonDemo();
}
}
6-22
CheckBoxDemo.java
import java.awt.*;
import java.awt.event.*;
public class CheckboxDemo implements ItemListener {
private Frame f;
public CheckboxDemo () {
f = new Frame("Checkbox Example");
Checkbox one = new Checkbox("One", true);
Checkbox two = new Checkbox("Two", false);
Checkbox three = new Checkbox("Three", false);
one.addItemListener(this);
two.addItemListener(this);
three.addItemListener(this);
f.setLayout(new FlowLayout());
f.add(one);
f.add(two);
f.add(three);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
6-23
CheckboxDemo.java
public void itemStateChanged(ItemEvent e) {
String state = "deselected";
if (e.getStateChange() == ItemEvent.SELECTED) {
state = "selected";
}
System.out.println(e.getItem() + " " + state);
}
public static void main(String args[]) {
CheckboxDemo bd = new CheckboxDemo();
}
}
6-24
CheckboxGroupDemo.java
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupDemo implements ItemListener {
private Frame f;
public CheckboxGroupDemo () {
f = new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox one = new Checkbox("One", cbg, true);
Checkbox two = new Checkbox("Two", cbg, false);
Checkbox three = new Checkbox("Three", cbg, false);
one.addItemListener(this);
two.addItemListener(this);
three.addItemListener(this);
f.setLayout(new FlowLayout());
f.add(one);
f.add(two);
f.add(three);
f.pack();
6-25
CheckboxGroupDemo.java
WindowDestroyer listener = new WindowDestroyer(); // window destroyer button
f.addWindowListener(listener);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
System.out.println(e.getItem() + " Selected");
}
public static void main(String args[]) {
CheckboxGroupDemo bd = new CheckboxGroupDemo();
}
}
6-26
ChoiceDemo.java
import java.awt.*;
import java.awt.event.*;
public class ChoiceDemo implements ItemListener {
private Frame f;
public ChoiceDemo () {
f = new Frame("Choice Example");
Choice choice = new Choice();
choice.addItem("First");
choice.addItem("Second");
choice.addItem("Third");
choice.addItemListener(this);
f.add(choice, BorderLayout.CENTER);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED)
System.out.println(e.getItem() + " Selected");
}
public static void main(String args[]) {
ChoiceDemo c = new ChoiceDemo();
}
}
6-27
CanvasDemo.java
import java.awt.*;
import java.awt.event.*;
public class CanvasDemo extends Canvas implements KeyListener {
private int index;
Color colors[] = {Color.red, Color.green, Color.blue};
public CanvasDemo () {
super();
}
public void paint(Graphics g) {
g.setColor(colors[index]);
g.fillRect(0, 0, getSize().width, getSize().height);
}
}
public void keyTyped(KeyEvent e) {
index++;
if (index == colors.length)
index = 0;
repaint();
}
6-28
CanvasDemo.java
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e){}
}
public static void main(String args[]) {
Frame f = new Frame("Canvas Example");
CanvasDemo can = new CanvasDemo();
can.setSize(150,150);
f.add(can, BorderLayout.CENTER);
can.requestFocus();
can.requestFocus();
can.addKeyListener(can);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
6-29
TextArea
TextComponents: TextArea and TextField
6-30
6-31
TextArea
6-32
TextAreaDemo.java
import java.awt.*;
import java.awt.event.*;
public class TextAreaDemo {
private Frame f;
private TextArea tf;
}
public TextAreaDemo () {
f = new Frame("TextArea");
tf = new TextArea("Welcome to Sognag!", 5, 30);
tf.addKeyListener(new NameHandler());
f.add(tf, BorderLayout.CENTER);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
6-33
TextAreaDemo.java
class NameHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
if (Character.isDigit(c))
e.consume();
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e){}
public static void main(String args[]) {
TextAreaDemo tfd = new TextAreaDemo();
}
}
6-34
TextField
6-35
TextField
6-36
TextFieldDemo.java
import java.awt.*;
import java.awt.event.*;
public class TextFieldDemo {
private Frame f;
private TextField tf;
}
public TextFieldDemo () {
f = new Frame("TextField");
tf = new TextField("Single Line", 30);
tf.addKeyListener(new NameHandler());
f.add(tf, BorderLayout.CENTER);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
6-37
TextFieldDemo.java
class NameHandler extends KeyAdapter {
public void keyPressed(KeyEvent e) {
char c = e.getKeyChar();
if (Character.isDigit(c))
e.consume();
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e){}
}
public static void main(String args[]) {
TextFieldDemo tfd = new TextFieldDemo();
}
6-38
6-39
List
6-40
List
6-41
List
6-42
ListDemo.java
import java.awt.*;
import java.awt.event.*;
public class ListDemo {
private Frame f;
private List l;
public ListDemo () {
f = new Frame("List");
l = new List(4, true);
l.add("Welcome");
l.add("to");
l.add("Sogang");
l.add("University");
f.add(l, BorderLayout.CENTER);
f.pack();
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
public static void main(String args[]) {
ListDemo tfd = new ListDemo();
}
}
6-43
Dialog
public class Dialog extends Window
– A Dialog is a top-level window with a title and a border that is typically used to
take some form of input from the user. The size of the dialog includes any area
designated for the border. The dimensions of the border area can be obtained
using the getInsets method, however, since these dimensions are platformdependent, a valid insets value cannot be obtained until the dialog is made
displayable by either calling pack or show. Since the border area is included in the
overall size of the dialog, the border effectively obscures a portion of the dialog,
constraining the area available for rendering and/or displaying subcomponents to
the rectangle which has an upper-left corner location of (insets.left, insets.top),
and has a size of width - (insets.left + insets.right) by height - (insets.top +
insets.bottom).
– The default layout for a dialog is BorderLayout.
– A dialog must have either a frame or another dialog defined as its owner when it's
constructed. When the owner window of a visible dialog is hidden or minimized,
the dialog will automatically be hidden from the user. When the owner window is
subsequently re-opened, then the dialog is made visible to the user again.
– A dialog can be either modeless (the default) or modal. A modal dialog is one
which blocks input to all other toplevel windows in the app context, except for any
windows created with the dialog as their owner. Dialogs are capable of
generating the following window events: WindowOpened, WindowClosing,
WindowClosed, WindowActivated, WindowDeactivated.
6-44
Dialog
Dialog box
– All of our user interface components have appeared inside a frame
window that was created in the application. This is the most common
situation if you write applets that run inside a Web browser. But if you
write applications, you usually want separate dialogs to pop up to get
information from the user.
– Dialog is a Frame with components
format: Dialog(Frame parent, Boolean modal)
Dialog(Frame parent, String title, Boolean modal)
class:
java.awt.Dialog
function: constructor (creates a dialog object)
Modal dialog: You need information from the user before you can
proceed
ex) Reading file needs file name before open it.
Modeless dialog: User can enter information in both the dialog and the
remainder of
the application. ex) tool bar
6-45
Dialog
format: dispose()
class:
java.awt.Window()
function: Dispose (eliminate) the window.
– How to use Dialog
• Create the Dialog object
• Place components in the Dialog box
• Process with actionPerformed()
saekDlg = new Dialog(this, “프레임 바탕색 설정”, false);
palChk = new Checkbox(“빨강”);
choChk = new Checkbox(“초록”);
paChk = new Checkbox(“파랑”);
saekDlg.add(new Button(“확인”));
saekDlg.add(palChk);
saekDlg.add(choChk);
saekDlg.add(paChk);
6-46
Checkbox and Button
are added in the Dialog
6-47
6-48
DialogDemo.java
import java.awt.*;
import java.awt.event.*;
public class DialogDemo implements ActionListener
{ private Frame f;
private Dialog saekDlg;
private Button pal, cho, pa, done;
public DialogDemo()
{
f = new Frame("Dialog Test");
saekDlg = new Dialog(f, "프레임 바탕색 설정", false);
pal = new Button("빨강"); saekDlg.add(pal);
cho = new Button("초록"); saekDlg.add(cho);
pa = new Button("파랑"); saekDlg.add(pa);
done = new Button("확인"); saekDlg.add(done);
pal.addActionListener(this);
cho.addActionListener(this);
pa.addActionListener(this);
done.addActionListener(this);
}
}
6-49
// dialog box saekDlg const.
DialogDemo.java
saekDlg.setLayout(new FlowLayout(FlowLayout.RIGHT));
saekDlg.setBackground(Color.lightGray);
// background change
saekDlg.pack();
f.setSize(200,200);
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
saekDlg.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int r=0,g=0,b=0;
if (e.getActionCommand() == "빨강") r=255;
if (e.getActionCommand() == "초록") g=255;
if (e.getActionCommand() == "파랑") b=255;
if(e.getActionCommand() == "확인") saekDlg.dispose();
f.setBackground(new Color(r, g, b));
// background change
f.repaint();
// frame renewal
}
public static void main(String[] args)
{ DialogDemo dd = new DialogDemo(); // frame construction
}
}
6-50
FileDialog
6-51
FileDialog
6-52
FileDialog
6-53
FDialogDemo.java
import java.awt.*;
public class FDialogDemo extends Frame
{ Image img;
boolean hdae;
String fname;
public FDialogDemo(String str)
{
super(str);
setBackground(Color.white);
FileDialog fDlg = new FileDialog(this, "이미지파일",
FileDialog.LOAD);
fDlg.setVisible(true);
fname = fDlg.getDirectory() + fDlg.getFile();
img = Toolkit.getDefaultToolkit().getImage(fname);
}
}
6-54
FDialogDemo.java
public void paint(Graphics g)
{
if (img != null)
g.drawImage(img, 100, 100,this);
}
public static void main(String[] args)
{
FDialogDemo frm = new FDialogDemo("파일 대화상자");
//frame construction
frm.setSize(500, 300);
// frame size : 500*300(pixel)
frm.setVisible(true);
WindowDestroyer listener = new WindowDestroyer();
frm.addWindowListener(listener);
}
}
6-55
Scrollbar
Scrollbar
format: Scrollbar(int orient, int value, int min, int max)
class:
java.awt.Scrollbar
constructor method that creates a scrollbar
orient: Scrollbar.HORIZONTAL, Scrollbar.VERTICAL
Event.UNIT_INCREMENT
value: initial position of scroll bar
Event.BLOCK_INCREMENT
min, max: range of scrollbar (default size is 0~100)
Event.TRACK
format: int getValue()
int setValue()
class:
java.awt.Scrollbar
Gets (Sets) the position of the scroll bar
Block increment
Unit increment
format: void setUnitIncrement(int n)
void
setBlockIncrement(int n)
class:
java.awt.Scrollbar
Sets the amount of increment (decrement) per the event
6-56
ScrollBarDemo.java
import java.awt.*;
import java.awt.event.*;
public class ScrollBarDemo implements AdjustmentListener
{ private Frame f;
private Scrollbar rScr, gScr, bScr;
private Label
rLbl, gLbl, bLbl;
public ScrollBarDemo()
{
f = new Frame("ScrollBar Test");
Panel p = new Panel();
p.setLayout(new GridLayout(2,3, 5,0)); // partition 2 * 3
f.setSize(500,300);
f.add("North", p);
// arrange panel p to the north of frame
p.add(rLbl = new Label("빨강"));
// arrange label in panel p
p.add(gLbl = new Label("초록"));
p.add(bLbl = new Label("파랑"));
// arrange Scrollbar in p panel
p.add(rScr = new Scrollbar(Scrollbar.HORIZONTAL, 50, 0, 0, 255));
p.add(gScr = new Scrollbar(Scrollbar.HORIZONTAL, 100, 0, 0, 255));
p.add(bScr = new Scrollbar(Scrollbar.HORIZONTAL, 200, 0, 0, 255));
}
6-57
ScrollBarDemo.java
rScr.addAdjustmentListener(this);
gScr.addAdjustmentListener(this);
bScr.addAdjustmentListener(this);
// increase/decrease amount when you press arrow button in scroll bar
rScr.setBlockIncrement(30);
gScr.setBlockIncrement(30);
bScr.setBlockIncrement(30);
// setting background of scrollbar
rScr.setBackground(Color.red);
gScr.setBackground(Color.green);
bScr.setBackground(Color.blue);
}
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
6-58
ScrollBarDemo.java
public void adjustmentValueChanged(AdjustmentEvent e)
{
if ( e.getAdjustmentType() == e.UNIT_INCREMENT ||
e.getAdjustmentType() == e.BLOCK_INCREMENT ||
e.getAdjustmentType() == e.UNIT_DECREMENT ||
e.getAdjustmentType() == e.BLOCK_DECREMENT ||
e.getAdjustmentType() == e.TRACK)
{
int r = rScr.getValue();
// value of bar in scroll bar
int g = gScr.getValue();
int b = bScr.getValue();
f.setBackground(new Color(r, g, b));
// background change
rLbl.setText("빨강 : " + r);
gLbl.setText("초록 : " + g);
bLbl.setText("파랑 : " + b);
}
}
}
f.repaint();
// for change of label value
// repainting
public static void main(String[] args)
{
ScrollBarDemo sb = new ScrollBarDemo();
}
6-59
Menu
– Menu bar : sits on top of the window and contains the name of the pulldown menus
– menu items : When the user clicks on a menu item, all menus are closed
and a message is sent to the program.
Adding menus is straightforward. You create a menu bar.
MenuBar mb = new MenuBar();
For each menu, you create a menu object.
Menu editMenu = new Menu(“Edit”);
You add menu items, separators, and submenus to the menu object.
editMenu.add(new MenuItem(“Copy”));
editMenu.addSeparator();
editMenu.add(new MenuItem(“Paste”));
6-60
MenuDemo.java
import java.awt.*;
import java.awt.event.*;
public class MenuDemo implements ActionListener
{ private Frame f;
Color saek;
public MenuDemo()
{
f = new Frame("MENU TEST");
MenuBar jumenu = new MenuBar();
Menu m1 = new Menu("색깔", true); // create menu 색깔
MenuItem m11 = new MenuItem("빨강");
MenuItem m12 = new MenuItem("파랑");
MenuItem m13 = new MenuItem("초록");
MenuItem m14 = new MenuItem("종료");
m1.add(m11);
// addition in menu m1
m1.add(m12);
m1.add(m13);
m1.addSeparator();
// menu separation line
m1.add(m14);
jumenu.add(m1); // addition of menu m1 in jumenu
}
Menu m2 = new Menu("모양");
// create menu 모양
MenuItem m21 = new MenuItem("사각형");
MenuItem m22 = new MenuItem("육면체");
m2.add(m21);
m2.add(m22);
jumenu.add(m2); // addition of menu m2 in jumenu
6-61
MenuDemo.java
m11.addActionListener(this);
m12.addActionListener(this);
m13.addActionListener(this);
m14.addActionListener(this);
m21.addActionListener(this);
m22.addActionListener(this);
f.setMenuBar(jumenu);
// setMenuBar in frame
f.setBackground(Color.white);
// frame background color : white
f.setSize(200,200);
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true);
}
}
public void actionPerformed(ActionEvent e) {
if
(e.getActionCommand().equals("빨강")) saek = Color.red;
else if (e.getActionCommand().equals("초록")) saek = Color.green;
else if (e.getActionCommand().equals("파랑")) saek = Color.blue;
else if (e.getActionCommand().equals("종료")) System.exit(0);
f.setBackground(saek);
f.repaint();
}
public static void main(String[] args)
{
MenuDemo md = new MenuDemo();
}
6-62
Checkbox Menu
Checkbox Menu : You can choose more then one item with checkbox
menu.
import java.awt.*;
public class mnCheck extends Frame
{
CheckboxMenuItem pal, cho, pa;
public mnCheck()
{
setTitle("설정/해제 메뉴");
MenuBar jumenu = new MenuBar();
Menu m = new Menu("바탕색");
pal = new CheckboxMenuItem("빨강"); m.add(pal);
cho = new CheckboxMenuItem("초록"); m.add(cho);
pa = new CheckboxMenuItem("파랑"); m.add(pa);
m.addSeparator();
m.add(new MenuItem("종료"));
jumenu.add(m);
6-63
CMenuDemo.java
import java.awt.*;
import java.awt.event.*;
public class CMenuDemo implements ActionListener, ItemListener
{ private Frame f;
Color saek;
CheckboxMenuItem pal, cho, pa;
public CMenuDemo()
{
f = new Frame("Checkbox Menu TEST");
MenuBar jumenu = new MenuBar();
Menu m1 = new Menu("색깔", true);
pal = new CheckboxMenuItem("빨강");
pa = new CheckboxMenuItem("파랑");
cho = new CheckboxMenuItem("초록");
MenuItem m14 = new MenuItem("종료");
m1.add(pal);
// addition in menu m1
m1.add(pa);
m1.add(cho);
m1.addSeparator();
// menu separation line
m1.add(m14);
jumenu.add(m1); // addition of menu m1 in jumenu
Menu m2 = new Menu("모양"); // create menu 모양
MenuItem m21 = new MenuItem("사각형");
MenuItem m22 = new MenuItem("육면체");
m2.add(m21);
m2.add(m22);
jumenu.add(m2); // addition of menu m2 in jumenu
6-64
CMenuDemo.java
pal.addItemListener(this);
pa.addItemListener(this);
cho.addItemListener(this);
m14.addActionListener(this);
m21.addActionListener(this);
m22.addActionListener(this);
f.setMenuBar(jumenu);
// setMenuBar in frame
f.setBackground(Color.white); // frame background color : white
f.setSize(200,200);
WindowDestroyer listener = new WindowDestroyer();
f.addWindowListener(listener);
f.setVisible(true); }
public void itemStateChanged(ItemEvent e) {
int r=0,g=0,b=0;
if (pal.getState()) r=255; // by each menu set
if (cho.getState()) g=255;
if (pa.getState()) b=255;
f.setBackground(new Color(r, g, b));
// change of background color
f.repaint();
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("종료")) System.exit(0);
}
6-65
Printing
– Allow the use of local printer conventions:
Frame f = new Frame(“Print Test”);
f.setVisible(true);
Toolkit t = f.getToolkit();
PrintJob job = t.getPrintJob(f, “MyPrintJob”, null);
Graphics g = job.getGraphics();
When users start a print operation, they see a printer selection dialog box.
They can then choose options, such as paper size, print quality, and
which printer to use.
f.printComponents(g);
The print() method asks a component to draw itself in this way.
Submit that page to the printer
g.dispose();
End the job and release the printer.
job.end();
6-66
PrintDemo.java
import java.awt.*;
public class PrintDemo extends Frame
{
public PrintDemo(String str) {
super(str);
}
public static void main(String[] args)
{
PrintDemo f = new PrintDemo("Print Test");
f.setVisible(true);
Toolkit t = f.getToolkit();
PrintJob job = t.getPrintJob(f, "MyPrintJob",null);
Graphics g = job.getGraphics();
}
}
6-67