Chapter 14: Intro to Swing Components
using CheckBox,buttonGroup, and JComboBox Classes
part of the UI environment.
responding to user events with a class
prepare your class to accept event messages tell your class to expect event to happen tell your class how to respond to events
setFont ( ) method
requires a Font object argument. To construct a Font object, there is need three arguments : typeface, style, and point size
Heavyweight Components
swing.JFrame, swing.JDialog, swing.JWindow, swing.JApplet, swing.JComponents, awt.Container, and awt.Component
JFrame Class (has four constructors)
1.) JFrame ( ) constructs a new frame that initially is invisible and has no title. 2.) JFrame ( String title ) create a new, initially invisible JFrame with the specified title. 3.) JFrame ( finish up page : 775. %%%%
Truths answers
A JTextField is a component into which a user can type a single line of text data; typically, a user types a line into a JTextField and then presses Enter on the keyboard or clicks a button with the mouse to enter the data. A JButton is a Component the user can click with a mouse to make a selection. Tool tips are popup windows that can help a user understand the purpose of components in an application; the tool tip appears when a user hovers the mouse pointer over the component.
truth and truth
A class can implement as many event listeners as it needs. 2. Any object can be notified of a mouse click or keyboard press as long as it implements the appropriate interface and is registered as an event listener on the appropriate event source. Every event-handling method accepts a parameter that represents the generated event.
truth and truth
A class that can react to ActionEvents includes an actionPerformed() method. You prepare your class to accept button-press events by importing the java.awt.event package into your program and adding the phrase implements ActionListener to the class header. Within an event-driven program, a component on which an event is generated is the source of the event, and an object that is interested in an event is a listener.
event handler
A method that executes because it is called automatically when an appropriate event occurs is an event handler. In other words, when you register a component (such as a JFrame) to be a listener for events generated by another component (such as a JCheckBox), you must write an event handler method. You cannot choose your own name for event handlers—specific method identifiers react to specific event types.
ActionListener
ActionLister is an interface a class containing a set of specification for methods that can be used Implementing this provides standard event method specification that allow the listener to work with the ActionEvents, which are the type of events that occur when a user clicks a button.
Alternative getsourse
Alternatively, you can also use the instanceof keyword to determine the source of the event. The instanceof keyword is used when it is necessary to know only the component's type, rather than what component triggered the event. For example, if you want to take some action when a user enters data into any JTextField, but not when an event is generated by a different Component type, you could use the method format shown in Figure 14-30. void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source instanceof JTextField) { // execute these statements when any JTextField // generates the event // but not when a JButton or other Component does } }
Container
Container is a type of component that holds other components so that you can treat a group of them as a single entity. Container are defined in the Container class Container can take forms as windows that can be drag, resize, minimize, restore, and close. The Container class is a child of the Component class. Therefore, every Contsiner object is a Component, and every component object ( including every container ) is an object
Event
Event accords when a user takes action on a component, such as clicking the mouse on a JButton object.
Changing a JLabel's Font
Font class from which creating an object that holds typeface and size information.
simple summery partly
For now, remember these tasks you must perform when you declare a class that handles an event: l The class that handles an event must either implement a listener interface or extend a class that implements a listener interface. For example, if a JFrame named MyFrame needs to respond to a user's clicks on a JCheckBox, you would write the following class header: public class MyFrame extends JFrame implements ItemListener If you then declare a class that extends MyFrame, you need not include implements ItemListener in its header. The new class inherits the implementation. l You must register each instance of the event-handling class as a listener for one or more components. For example, if MyFrame contains a JCheckBox named myCheckBox, then within the MyFrame class you would code: myCheckBox.addItemListener(this); The this reference is to the class in which myCheckBox is declared—in this case, MyFrame.
Example using the getSourse
For example, if a JFrame contains two JButtons named option1 and option2, you can use the decision structure in the method in Figure 14-29 to take different courses of action based on the button that is clicked. Whether an event's source is a JButton, JTextField, or other Component, it can be assigned to an Object because all components descend from Object. public void actionPerformed(ActionEvent e) { Object source = e.getSource(); if(source == option1) //execute these statements when user clicks option1 else }
Example JLabel Code
For example, you can create a JLabel named greeting that holds the words "Good day" by writing the following statement: JLabel greeting = new JLabel("Good day"); You then can add the greeting object to the JFrame object named aFrame using the add() method as follows: aFrame.add(greeting); import javax.swing.*; public class JFrame3 { public static void main(String[] args) { final int FRAME_WIDTH = 250; final int FRAME_HEIGHT = 100; JFrame aFrame = new JFrame("Third frame"); aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT); aFrame.setVisible(true); aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel greeting = new JLabel("Good day"); aFrame.add(greeting); } } The counterpart to the add() method is the remove() method. The following statement removes greeting from aFrame: aFrame.remove(greeting); If you add or remove a component from a container after it has been made visible, you should also call the invalidate(), validate(), and repaint() methods, or else you will not see the results of your actions. The invalidate() and validate() methods are part of the Container class, and the repaint() method is part of the Component class.
Additional JLabel Objects
Frames often contain other windows features such as JTextFiels, JButton, and tool tips.
Simple JFrame Code
Import javax. swing.*; public class JFrame1 { public static void main (String [ ] args) { JFrame aFrame = new JFrame ( "first frame"); aFrame.setSize(250,100); AFrame.setVisable(true); } } All three statements in the main() method are important. After instant I ate a Frame, if setVisable(true), you do not see the JFrame,and if the set size is not available, then only the title bar will be visible because the JFrame size is 0x0 by default. Also to make a frame visible, some java programmers use the show( ) methods instead of the setVisable ( ) method.
Adding JButtons
JButton is a Component the user can click with a mouse to make a selection. there are 5 JButton constructors: 1.) public JButton ( ) create a button with no set of text 2.) public JButton (Icon icon) creates a button with an icon of a type Icon or ImageIcon 3.)public JButton(String text) crates a button with text 4.)public JButton(string text, Icon icon) creates a button with initial text and an icon of type Icon or ImageIcon 5.)public JButton(Action a) creates a button in which properties are taken form the Action supplied ( Action is a Java class).
Closing a JFrame
JFrame.EXIT_ON_CLOSE It will exits the program when the JFrame is closed. WindowConstants.DISPOSE_ON_CLOSE It will close the frame, depose of the JFrame object, and keeps running the application. WindowConstants.DO_NOTHING_ON_CLOSE keeps the JFrame open and continues running. In other words, it disables the Close button. WindowConstants.HIDE_ON_CLOSE closes the JFrame and continues running; this is the default operation that you frequently want to override. Control + C
Available constructors for the JLabel class
JLabel () create a JLAbel instance with no image and with an empt string for the title. JLAbel ( Icon Image ) create a JLAbel instance with the specified image JLAbel( Icon image, int horizontalAlignment ) create a JLabel instance with the specified image and horizontal alignment JLabel(String text) creates a JLabel instance with the specified text. JLabel(String text, Icon icon, int horizontalAlignment) creates a JLabel instance with the specified text, image, and horizontal alignment. JLabel(String text, int horizontalAlignment) creates a JLabel instance with the specified text and horizontal alignment.
Using the JLabel Class
JLabel is a built-in Java Swing class that holds text that can be displayed this component can be placed in a JFrame.
Pixels
Pixar's are the picture element, or tiny dots of light, that make up the image on the computer monitor. firstFrame.setSize( 250,100); firstFrame.setTitle(" My Frame");
Swing components
Swing components are UI elements such as dialog boxes and buttons; you can recognize their names because they begin with a J. Swing components is a descendent of a JComponent, which in return inherits from the java.awt.Container class. Insert the import statement import javax.swing.x; at the beginning of the Java program files so that the Swing Component can be used. **** import javax.swing.*; The x originally stood for extension, so named because the Swing classes were an extension of the original Java language specifications. The Component class is a child of the Object class.
how to respond to Events
The ActionListener interface contains the actionPerformed(ActionEvent e) method specification. When a class, such as a JFrame, has registered as a listener with a Component such as a JButton, and a user clicks the JButton, the actionPerformed() method executes. You implement the actionPerformed() method, which contains a header and a body, like all methods. You use the following header, in which e represents any name you choose for the Event (the JButton click) that initiated the notification of the ActionListener (which is the JFrame): public void actionPerformed(ActionEvent e) The body of the method contains any statements that you want to execute when the action occurs. You might want to perform mathematical calculations, construct new objects, produce output, or execute any other operation. For example, Figure 14-26 shows a JFrame containing a JLabel that prompts the user for a name, a JTextField into which the user can type a response, a JButton to click, and a second JLabel that displays the name entered by the user. The actionPerformed() method executes when the user clicks the pressMe JButton; within the method, the String that a user has typed into the JTextField is retrieved and stored in the name variable. The name is then used as part of a String that alters the second JLabel on the JFrame. Figure 14-27 shows an application that instantiates a JHelloFrame object and makes it visible.
JFrame Example
The following two statements constitute two JFrame : one with a title and another with no title JFrame firstFrame = new JFrame( " Hello"); JFrame secondFrame = new JFrame ();
Info involving JButton
To create a JButton with the label "Press when ready", you can write the following: JButton readyJButton = new JButton("Press when ready"); You can add a JButton to a JFrame (or other container) using the add() method. You can change a JButton's label with the setText() method, as in: readyJButton.setText("Don't press me again!"); You can retrieve the text from a JButton and assign it to a String object with the getText() method, as in: String whatsOnJButton = readyJButton.getText();
Tool Tips
Tool tips are popup windows the can help a user understand the purpose of components in a an applications, the tool tip appears when a user hovers the mouse pointer over the components using the setToolTipText ( ) method displays helpful text and passing and appropriate String to it. ex. button.setToolTipText("Click this button");
User Interface (UI) components
UI components are buttons, text fields, and other components with which the user can instersct.
JFrame Class
Usually when creating a JFrame is to place objects within it for display. Side note : object class is defined in the Java.lang package which is automatically imported eveytime a Java programe is written .however Objects descendants are not automatically imported.
Listener
an object that is interested in a event is a listener however not all objects listen for all possible events For it to be listen the object event must be register the object as a listener for the source.
style argument
applies an attribute to display text and is one of three values Font.PLAIN, Font.BOLD, Font.Italic
Understanding Swing Event Listeners
can implement as many event listeners as needed example: if the class might need to respond to both a mouse button press and a keyboard key press , implementing both ActonListener and KeyListerner interface *** an event occurs every time a user types a character to likes a mouse button
setText( ) method
changing the text in a JLAbel by using the Component class setText() method with the JLabel object and passing a String to it ex. greeting.setText("Howdy"); can also retrieve the text in a JLabel ( or other Component ) by using getText() method which will return the current stored String.
JCheckBox
consists label positioned beside a square. click the square to display or remove a check mark the option for the user to turn on or off page 812 continue
TextField is Editable by default
creating a boolean value to the setEditable (0 method to change the JTextField editable status. example if you want to give the user a limited number of toys to answer a questions correctly . use . if (attempts > LIMIT) response.setEditable(false);
getSourse
different actins to occur depending on weather the user clicks the button or presses Enter , you must determine the source of the event within the actionPerformae() method ,using the etSourse ( ) method of the object sent to determine which component generated the event For example, within a method with the header public void actionPerformed(ActionEvent e), e is an ActionEvent. ActionEvent and other event classes are part of the java.awt.event package and are subclasses of the EventObject class. To determine what object generated the ActionEvent, you can use the following statement: Object source = e.getSource();
Simple ActionListener Code
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class JHelloFrame extends JFrame implements ActionListener { JLabel question = new JLabel("What is your name?"); Font bigFont = new Font("Arial", Font.BOLD, 16); JTextField answer = new JTextField(10); JButton pressMe = new JButton("Press me"); JLabel greeting = new JLabel(""); final int WIDTH = 275; final int HEIGHT = 225; public JHelloFrame() { super("Hello Frame"); setSize(WIDTH, HEIGHT); setLayout(new FlowLayout()); question.setFont(bigFont); greeting.setFont(bigFont); add(question); add(answer); add(pressMe); add(greeting); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pressMe.addActionListener(this); //when you Click Button the actionPerformed executes answer.addActionListener(this); //when you Enter the Key the actionPerformed executes } public void actionPerformed(ActionEvent e) { String name = answer.getText(); String greet = "Hello, " + name; greeting.setText(greet); } }
Simple JLabel Font Example
import javax.swing.*; import java.awt.*; public class JFrame4 { public static void main(String[] args) { final int FRAME_WIDTH = 250; final int FRAME_HEIGHT = 100; JFrame aFrame = new JFrame(" frame"); aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT); aFrame.setVisible(true); aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel greeting = new JLabel("Good day"); greeting.setFont(headlineFont); aFrame.add(greeting); } } the import java.awt.*; was added because it contains the Font class package.
Simple Layout Manager Code
import javax.swing.*; import java.awt.*; public class JFrame6 { public static void main(String[] args) { final int FRAME_WIDTH = 250; final int FRAME_HEIGHT = 100; JFrame aFrame = new JFrame("Sixth frame"); aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT); aFrame.setVisible(true); aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel greeting = new JLabel("Hello"); JLabel greeting2 = new JLabel("Who are you?"); aFrame.setLayout(new FlowLayout()); aFrame.add(greeting); aFrame.add(greeting2); } } because a FlowLayout is used the two Jalbel paper side by side. if there was more components , they would continue to be laced side by side across the JFrame until there was no more room .
JTextFields
is a component into which a user can type a single line text data. Text data comprises any characters you can enter from the keyboard, including numbers and punctuation. You can construct a JTextField object using one of several constructors: public JTextField() constructs a new JTextField. public JTextField(int columns) constructs a new, empty JTextField with a specified number of columns. public JTextField(String text) constructs a new JTextField initialized with the specified text. public JTextField(String text, int columns) constructs a new JTextField initialized with the specified text and columns. For example, to provide a JTextField that allows enough room for a user to enter approximately 10 characters, you can code the following: JTextField response = new JTextField(10); To add the JTextField named response to a JFrame named frame, you write: frame.add(response); Several other methods are available for use with JTextFields. The setText() method allows you to change the text in a JTextField (or other Component) that has already been created, as in the following: response.setText("Thank you");
setBounds ( )
is a method that ca be used so that if a JFrame that produces the output with two JFrames there s no need to move one of the JFrame object to view the other.
point size argument
is an integer that represent about 1/72 of an inch. Printed text is commonly 12 points; a headline might be 20 points
setLocation ()
is an object class that can be used with a JFrame. to use this method , providing horizontal and vertical position values as methods arguments
Preparing Your Class to Accept Event Messages
java.awt.event importing this package prepares the class to accept button-press events. adding the phrase : implements ActionListener to the class header. aslo, using this package it includes event classes with names such as ActionEvent, ComponentEvent, and TextEvent.
Actionevent (" addActionListener() method
telling the class to expect event to happen You tell your class to expect ActionEvents with the addActionListener() method. this : this word means "this current object," declared a JButton named aButton. it performs an action when click aButton, aButton is the source of a message. so the code aButton.addActionListener(this); causes any ActionEvent messages (button clicks) that come from aButton to be sent to "this current object."
Customizing a JFrame Appearance
the icons and buttons are known as window decoration. By default windows decoration are supplied by the operating system A look and feel is the default appearance and behavior of any user interface.
BorderLayout
the normal (default) behavior of a JFrame is to use a layout format named BorderLayout. It divides a container into regions when you don't specify a region in which to place a component ( as the JFrame5 program fails to do), all the components are placed in the same region, and they obscure each other.
Using the setEnabled() Method
the setEnabled() method to make a component available or unavailable by passing true or false to it, respectively.
Event-Driven Program
the user might initiate any number of events inane order. For example, if you use a word-processing program, you have dozens of choices at your disposal at any time. You can type words, select text with the mouse, click a button to change text to bold, click a button to change text to italic, choose a menu item, and so on. With each word-processing document you create, you choose options in any order that seems appropriate at the time. The word-processing program must be ready to respond to any event you initiate.
More then one component is added and register to a JFrame
this might be necessary to determine which component was used to imitate an event so that the user will be able to see the message after either clicking the button or pressing Enter in the JTextField. In this case from above code , designate both the pressMe button and the answer text field to be message sources by using the addActionListener ( ) method with each , as follows: pressMe.addActionListener(this); answer.addActionListener(this); this two statements make the JFrame (this ) the receiver of messages from either object.
Given a JLabel a new Font
to gibe JLabel a new Font, create a Font Object. Font headlineFont = new Font ("Monospaced", Font.BOLD,36); the name has to be double quoted can use the setFont( ) method t passing the Font to a JLAbel with the statement such as: gretting.setFont(headlineFont);
Layout Manager
to place multiple components at specified position in a container so that they do not hide each other, nut explicitly use the layout manager.Its a class that controls component positioning. The flow layout manager places components in a row, and when is filled , components automatically spill into the next row. Three constant defined in the flow layout manager class that specify who components are positioned in each row of their container: they are FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER ex. FlowLayout flow = new Flowlayout(FlowLayout.RIGHT); If you do not specify how components are laid out, by default they are centered in each row. **** A more compact syntax that uses an anonymous FlowLayout object is: aFrame.setLayout(new FlowLayout()); ****
typeFace argument
typeface argument : the Font constructor is a String representing a font. Common font like Arial, Century, Time New Roman. if the program runs might not access to the requested font, and if necessary , it substitutes a default font .
Extending the JFrame Class
using the keyword extends in the class creates a child class followed by the parent class name. also you ca call the parent classes constructor using the keyword SUPER, and when you call super(), the call must be the first statement in the constructor . the following two statements have identical meanings: setSize(WIDTH, HEIGHT); this.setSize(WIDTH, HEIGHT); When a class descends from JFrame, you can use super() or setTitle() to set the title within the child's constructor. However, super() does not work in other methods. The advantage of creating a child class of JFrame is that you can set the JFrame's properties within your object's constructor so it is automatically endowed with the features that you have specified. When you extend a JFrame to create a new custom class, you can decide which attributes you want to set within the class and which you want to leave to the applications that will use the class.
Using a Layout Manager
when adding multiple components to a JFrame or other container, instructions are needed for the layout of the components. import javax.swing.*; import java.awt.*; public class JFrame5 { public static void main(String[] args) { final int FRAME_WIDTH = 250; final int FRAME_HEIGHT = 100; JFrame aFrame = new JFrame("Fifth frame"); aFrame.setSize(FRAME_WIDTH, FRAME_HEIGHT); aFrame.setVisible(true); aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel greeting = new JLabel("Hello"); JLabel greeting2 = new JLabel("Who are you?"); } } the out put of this application will just be who are you? even tho two JLabel object are created the last one added is visible. thats because the second Label has been placed onto of the first one, totally obscuring it .
JTextField that can be used to clear text after user has has entered it
which assigns an empty string to the text: response.setText(""); The getText() method allows you to retrieve the String of text in a JTextField (or other Component), as in: String whatUserTyped = response.getText();
Source
within an event-drive program, a component on which an event is generated is the source of the event. an example of a course is when a user clicks on a button; text field that a user can use ti enter text is another source