1.23k likes | 1.37k Views
Object-Oriented Programming. Chapter 5 (1): GUI in Java. Agenda. Layeout Mangement FlowLoyout BorderLayout GridLayout …. Introduction Simple GUI-Based IO with JOptionPane . AWT vs swing Containers and Components Introduction to Components Jlable Jbotton …. Introduction.
E N D
Object-Oriented Programming Chapter 5 (1): GUI in Java
Agenda • LayeoutMangement • FlowLoyout • BorderLayout • GridLayout • …. • Introduction • Simple GUI-Based IO with JOptionPane. • AWT vs swing • Containers and Components • Introduction to Components • Jlable • Jbotton • …
Introduction • A graphical user interface (GUI) presents a user-friendly mechanism for interacting with an application. • It gives an application a distinctive “look” and “feel.” Providing different applications with consistent, intuitive user interface components allows users to be somewhat familiar with an application, so that they can learn it more quickly and use it more productively. • GUIs are built from GUI components. These are sometimes called controls orwidgets—short for window gadgets—in other languages. • A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition.
Introduction • A GUI component is an object with which the user interacts via the mouse, the keyboard or another form of input, such as voice recognition. • In this chapter you will earn about many of Java’s GUI components.
Simple GUI-Based I/O with JOptionPane • The following simple addition application uses two input dialogs to obtain integers from the user and a message dialog to display the sum of the integers the user enters. import javax.swing.JOptionPane; public class Addition { public static void main( String args[] ) { String firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); int number1 = Integer.parseInt( firstNumber ); String secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); int number2 = Integer.parseInt( secondNumber ); int sum = number1 + number2; // add numbers JOptionPane.showMessageDialog( null, "The sum is " + sum, "Sum of Two Integers", JOptionPane.PLAIN_MESSAGE ); } }
Simple GUI-Based … • Java’s JOptionPaneclass(package javax.swing)providesprepackaged dialog boxes for both input and output. • These dialogs are displayed by invoking staticJOptionPanemethods. • showInputDialogmethod displays an input dialog using the method’s String argument ("Enter first integer") as a prompt . It has a text box and two buttons ok and Cancel • showMessageDialogmethod is used to display a message dialog containing the sum. • Thefirstargument helps the Java application determine where to position the dialog box. • The valuenullindicates that the dialog should appear in the center. • It can also be used to specify that the dialog should appear centered over a particular window of the computer screen.
Simple GUI-Based… • Thesecondargument is the message to display—in this case, the result of concatenating the String "The sum is " and the value of sum. • Thethirdargument—"Sum of Two Integers"—represents the string that should appear in the dialog’s title bar at the top of the dialog. • The fourthargument:- JOptionPane.PLAIN_MESSAGE—is the type of message dialog to display. A PLAIN_MESSAGEdialog does not display an icon to the left of the message. Other possible constants are: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE • Class JOptionPane provides several overloaded versions of methods showInputDialogand showMessageDialog, as well as methods that display other dialog types.
AWT vs Swing • Java has two GUI packages, the original Abstract Windows Toolkit (AWT) and the newer Swing. • When java was introduced, the GUI classes were bundled in a library known as Abstract Windows Toolkit(AWT). • AWT (Abstract Window Toolkit) is Java’s original set of classes for building GUIs. • Uses peer components of the OS; heavyweight • AWT uses the native operating system's window routines so the visual effect is dependent on the run-time system platform.
AWT vs Swing • For every platform on which Java runs, the AWT components are automatically mapped to the platform-specific components through their respective agents, known as peers. • Not truly portable: looks different and lays out inconsistently on different OSs. The application's GUI components display differently on each platform. • AWT is adequate for many applications but it is difficult to build an attractive GUI
AWT vs Swing • Swing is designed to solve AWT’s problems (present since Java 2 ) • 99% java; lightweight components • Drawing of components is done in java • Swing GUI components allow you to specify a uniform look-and-feel for your application across all platforms. • Lays out consistently on all Oss • Much bigger set of built-in components • Uses AWT event handling
AWT vs Swing… • Swing is built “on top of” AWT, so you need to import AWT and use a few things from it • Swing is bigger and slower • Swing is more flexible and better looking • Swing and AWT are incompatible--you can use either, but you can’t mix them • Actually, you can, but it’s tricky and not worth doing • Basic components/controls are practically the same in both • AWT: Button b = new Button ("OK"); • Swing: JButton b = new JButton("OK"); • Swing gives far more options for everything (buttons with pictures on them, etc.) • AWT classes are contained inside package java.awt while swing classes are located in package javax.swing.
GUI Classes • The GUI classes can be classified into three groups: container class, helper class, and component classes. Container classes • A GUI is built by putting components/controls into containers. • Container is used to group components. Frames, Panels and applets are examples of containers. • Important Container classes areJFrame, JApplet, and JPanel.
GUI Classes JFrame • A resizable, movable window with title bar and close button. Usually it contains JPanels. • It is a containers that holds other Swing user-interface components in Java GUI application. JPanel • A region internal to a JFrame or another JPanel. Used for grouping components together. Optionally bounded by a visible border. Lives inside some enclosing Container. • Panels can be nested. You can place panels inside a container that includes a panel.
GUI Classes… • The terms “pane” and “panel” are used interchangeably in Java. • If a frame is a window, a pane is the glass. • Panes hold a window’s GUI components. • Every frame has at least one pane, the default “Content Pane” JApplet • Is a subclass of Applet . • represents the featureless Window provided by the browser for an Applet to run in.
Container Classes Container classes can contain other GUI components.
GUI Classes… GUI Components or controls (also known as "widgets") • Are the basic user interface elements the user interacts with: labels, buttons, text fields, ... • The visual arrangement of the components depends on the container's layout. • When the user does something to a component, the component's listener is sent an event.
Swing GUI Components • Input Components • Buttons ( JButton, JRadioButtons, JCheckBox) • Text (JTextField, JTextArea) • Menus (JMenuBar, JMenu, JMenuItem) • Sliders (JSlider) • JComboBox (uneditable) (JComboBox) • List (Jlist ) • Information Display Components • JLabel • Progress bars (JProgressBar) • Tool tips (using JComponent'ssetToolTipText(s) method) • Choosers • File chooser (JFileChooser) • Color chooser (JColorChooser)
Swing GUI Components … • More complex displays • Tables (JTable) • Trees (JTree) • Formatted Text • Every GUI components has • Properties • Methods • Events JButton
GUI Class… GUI Helper Classes • They are used to describe the properties of GUI components such as graphics context, colors, fonts, and dimension. Graphics • Is an abstract class that provides a graphical context for drawings strings, lines, and simple shapes. Color: • Deals with the colors of GUI components. For example:- you can specify background colors in components like Jframe and Jpanel. You can specify colors of lines, shapes,…..
GUI Class… Font • Specify fonts for the text and drawings on GUI components. Example:- You can specify the font type(e.g. SansSerif), style (e.g. bold), and size(e.g. 24 points) for the text on the button. LayoutManager • Is an interface whose instances specify how components are arranged in a container. • The helper classes are in the java.awt package. The Swing components do not replace all the classes in AWT, only AWT GUI components classes (e.g. Button, TextField, TextArea). The AWT is helper classes remain unchanged.
Steps to build a GUI • Make a Container – you need to create either a frame or an applet to hold the user-interface components. • Create some more Components (buttons, text areas, etc.). • Add your Components to your display area - Choose a layout manager. • Attach Listeners to your Components - interacting with a Component causes an Event to occur.
Creating a Frames Frame • Is an independent window that has decorations such as a border, a title and buttons for closing, minimizing and maximizing the window. • Frame is a window that is not contained inside another window. • Can be moved around on the screen independently of any other GUI windows. • Applications with a GUI typically use at least one frame. • Frame is the basis to contain other user interface components in Java GUI applications.
Frame • The JFrame class can be used to create windows. • For Swing GUI programs, use JFrame class to create widows.
JFrames… JFrame Class Methods
JFrames… JFrame Class Methods public void setBounds(int x, int y, int width, int height) • Specifies the size of the frame and the location of the upper • left corner. • This puts the upper left corner at location (x, y), where x the • the number of pixels from the left of the screen and y is is the • number from the top of the screen. height and width are as • before.
JFrames… JFrame Class Methods public void setDefaultCloseOperation(int mode) • Is used to specify one of several options for the close button. Use one of the following constants to specify your choice: • JFrame.EXIT_ON_CLOSE:- Exit the application. • JFrame.HIDE_ON_CLOSE:- Hide the frame, but keep the application running. • JFrame.DO_NOTHING_ON_CLOSE:-Ignore the click.
JFrame… import javax.swing.*; public class JFrameSample { public static void main(String[] args) { JFrame frame = new JFrame(“First JFrame"); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }
JFrame… • The frame is not display until the frame.setVisibile(true) method is invoked. • frame.setSize(400, 300)specifies that the frame is 400 pixels wide and 300 pixels high. • If thesetSizeand setVisible methods are both defined in the component class, they are inherited by the JFrame class. • Invoking setLocationRelativeTo(null)centers the frame on the screen.
JFrame… • Invoking setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) tells the program to terminate when the frame is closed. • If you forget to call setDefaultCloseOperation() you will get JFrame.HIDE_ON_CLOSE by default. Thus the program does not terminate when the frame is closed. In that case, you have to stop the program by pressing Ctrl + C.
JFrame… importjavax.swing.JFrame; publicclass Simple extends JFrame { public Simple() { setSize(300, 200); setTitle("First JFrame"); setLocationRelativeTo(null); SetDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } publicstaticvoid main(String[] args) { Simple simple = new Simple(); } }
JFrame… • The setTitle(String text) method is defined in the • java.awt.Frame class. • Since JFrame is subclass of Frame, you can use it to se a title • for an object of JFrame. • The constructor Simple() does not explicitly invoke • the constructor JFrame(). But the constructor JFrame() is • invoked implicitly. (Constructor Chaining).
GUI Components • Introduces the frequently used GUI components
JButton • A button is a component that triggers an action event when clicked. • Swing provides regular buttons, toggle buttons, check box buttons, and radio buttons. • The common features of these buttons are generalized in javax.swing.AbstractButton. • JButtoninherits AbstractButton and provides several constructors to create buttons.
JButton JButtonConstructors.
JButton The following are JButton constructors: JButton() • Creates a default button with no text and icon. JButton(Icon icon) • Creates a button with an icon. JButton(String text) • Creates a button with text. JButton(String text, Icon icon) • Creates a button with text and an icon.
JButton JButton Properties • text • icon • mnemonic • horizontalAlignment • verticalAlignment • horizontalTextPosition • verticalTextPosition • iconTextGap
JButton Some UsefulJButtonMethods public void setText(String text) • Sets the button's text. public String getText() • Returns the button's text. public void setEnabled(boolean b) • Enables (or disables) the button.
JButton Some usefulJButtonMethods public void setSelectedIcon(IconselectedIcon) • Sets the selected icon for the button. public booleanisSelected() • Returns the state of the button. True if the toggle button is selected, false if it's not.
JLabel A label is a display area for a short text(a non-editable), an image, or both.
JLabel The constructors for labels are as follows • JLabel() • Creates a default label with no text and icon. • JLabel(String text) • Creates a label with text. • JLabel(Icon icon) • Creates a label with an icon. • JLabel(String text, inthorizontalAlignment) • Creates a label with an text and the specified horizontal • alignment.
JLabel The constructors for labels are as follows: • JLabel(Icon icon, inthorizontalAlignment) • Creates a label with an icon and the specified horizontal • alignment. • JLabel(String text, Icon icon, int • horizontalAlignment) • Creates a label with text, an icon, and the specified horizontal • alignment.
JLabel JLabelProperties • JLabel inherits all the properties from JComponent and has many properties similar to the ones in JButton, such as text, icon, horizontalAlignment, verticalAlignment, horizontalTextPosition, verticalTextPosition, andiconTextGap.
JLabel Jlabel… Some UsefulJLabelMethods public String getText() • Returns a string containing the text in the label component public void setText(String) • Sets the label component to contain the string value public Icon getIcon() • Returns the graphic image (icon) that the label displays. public void setIcon(Icon icon) • Defines the icon this component will display. If the value of icon is null, nothing is displayed.