Pemrograman Berorientasi Objek
Bab 7 – GUI Programming
Introduction
User sebuah sistem menilai sebuah app berdasarkan 2 hal utama: Fungsionalitas Interface
Fungsionalitas berbicara mengenai apa yang bisa dilakukan app untuk membantu user
Interface berbicara mengenai tampilan app yang user hadapi untuk sarana interaksi dengan sistem
App yang baik adalah app selain bekerja dengan baik juga harus memiliki interface yang menarik dan mampu memberikan kemudahan interaksi user (user-friendly)
Look At These!
Dari kedua app di atas, app manakah yang lebih Anda sukai untuk Anda gunakan? Manakah yang lebih menarik?
GUI – Graphical User Interface
Untuk membangun app yang menarik sudah saatnya mengenal GUI
GUI dibangun berdasarkan komponen – komponen grafikal yang disusun sedemikian rupa sehingga membentuk suatu tampilan yang lengkap sesuai dengan kehendak programmer
Komponen – komponen GUI pada umumnya dibangun menggunakan konsep OOP
GUI Components
A Form
A Label
A Text Field
A Password Field
A Button
GUI Component Category
Komponen GUI dibagi ke dalam 2 kelompok kategori:ContainerContainment
Container
Container adalah component yang mampu menampung komponen lain dan merupakan wadah untuk meletakkan containment component
Misalkan form, panel
Containment Component
Containment adalah component yang harus diletakkan ke dalam sebuah container
Sebuah containment component hanya boleh berada dalam sebuah container
Biasanya containment component adalah komponen2 yg digunakan untuk interaksi dengan user seperti label, input, tombol dkk
Know Java-based GUI
Java menyediakan 2 buah sarana untuk bermain dengan GUI:Abstract Window Toolkit (AWT)Swing
Keduanya menyediakan fasilitas yang hampir serupa dalam mengembangkan app berbasis GUI
Swing merupakan perkembangan dari AWT
Swing
Teach SwingWhy not AWT?
App yang dibangun menggunakan AWT sering mengalami inconsistent dalam hal tampilan jika dijalankan di platform yang berbeda
Swing Component Classification
Top-Level Containers The components at the top of any Swing containment hierarchy.
General-Purpose Containers Intermediate containers that can be used under many different
circumstances. Special-Purpose Containers
Intermediate containers that play specific roles in the UI. Basic Controls
Atomic components that exist primarily to get input from the user; they generally also show simple state.
Uneditable Information Displays Atomic components that exist solely to give the user information.
Editable Displays of Formatted Information Atomic components that display highly formatted information that (if
you choose) can be edited by the user.
Top-Level Containers
Frame ( and JFrame)
Dialog ( and JDialog)
Applet (and JApplet)
General-Purpose Containers
Panel ( and JPanel)
JToolBarJScrollPane
JTabbedPane
JSplitPane
Special-Purpose Containers
JLayeredPane JInternalFrames
Root Pane
Basic Controls
JCheckBoxJRadioButtonJButton
JMenuJMenuItem
List ( and JList) Choice ( and JComboBox)
JTextField
JSlider
Uneditable Information Displays
Label ( and JLabel)
JProgressBar
JToolTip
Editable Displays of Formatted Information
JTree JText JTable
FileDialog ( and JFileChooser)JColorChooser
Know Some Components in Detail
Beberapa komponen yang akan dikenalkan secara mendetail adalah sebagai berikut: JOptionPane JFrame JTextField JPasswordField JLabel JButton
Komponen yang lain silakan dipelajari pada saat asisten + dipelajari sendiri
JOptionPane
JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.
Static method:
JOptionPane Cont`
static int showConfirmDialog(Component parentComponent, Object message) Brings up a dialog with the options Yes, No and Cancel; with the title, Select an Option
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType) Brings up a dialog where the number of choices is determined by the optionType parameter
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType) Brings up a dialog where the number of choices is determined by the optionType parameter, where the messageType parameter determines the icon to display.
static int showConfirmDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon) Brings up a dialog with a specified icon, where the number of choices is determined by the optionType parameter.
JOptionPane Cont`
static String showInputDialog(Component parentComponent, Object message) Shows a question-message dialog requesting input from the user parented to parentComponent.
static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user and parented to parentComponent.
static String showInputDialog(Component parentComponent, Object message, String title, int messageType) Shows a dialog requesting input from the user parented to parentComponent with the dialog having the title title and message type messageType.
static Object showInputDialog(Component parentComponent, Object message, String title, int messageType, Icon icon, Object[] selectionValues, Object initialSelectionValue) Prompts the user for input in a blocking dialog where the initial selection, possible selections, and all other options can be specified.
static String showInputDialog(Object message) Shows a question-message dialog requesting input from the user.
static String showInputDialog(Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user, with the input value initialized to initialSelectionValue.
JOptionPane Cont`
static void showMessageDialog(Component parentComponent, Object message) Brings up an information-message dialog titled "Message".
static void showMessageDialog(Component parentComponent, Object message, String title, int messageType) Brings up a dialog that displays a message using a default icon determined by the messageType parameter.
static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) Brings up a dialog displaying a message, specifying all parameters.
static int showOptionDialog(Component parentComponent, Object message, String title, int optionType, int messageType, Icon icon, Object[] options, Object initialValue) Brings up a dialog with a specified icon, where the initial choice is determined by the initialValue parameter and the number of choices is determined by the optionType parameter.
JOptionPane Cont`
Parameter description: parentComponent
Defines the Component that is to be the parent of this dialog box. It is used in two ways: the Frame that contains it is used as the Frame parent for the dialog box, and its screen coordinates are used in the placement of the dialog box. This parameter may be null.
messageA descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant.
messageTypeDefines the style of the message. The possible values are: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE
optionTypeDefines the set of option buttons that appear at the bottom of the dialog box: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION, OK_CANCEL_OPTION
JOptionPane Cont`
optionsA more detailed description of the set of option buttons that will appear at the bottom of the dialog box. The usual value for the options parameter is an array of Strings. But the parameter type is an array of Objects. A button is created for each object depending on its type:
ComponentThe component is added to the button row directly.
IconA JButton is created with this as its label.
otherThe Object is converted to a string using its toString method and the result is used to label a JButton.
JOptionPane Cont`
icon
A decorative icon to be placed in the dialog box. A default value for this is determined by the messageType parameter.
title
The title for the dialog box. initialValue
The default selection (input value).
JOptionPane Cont`
When one of the showXxxDialog methods returns an integer, the possible values are: YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION
JFrame
JFrame adalah container paling mendasar dalam pembuatan java-desktop based app
Merupakan top-level container Beberapa constructor:
JFrame() Constructs a new frame that is initially invisible.
JFrame(String title) Creates a new, initially invisible Frame with the specified title.
JFrame Cont`
Beberapa method: void remove(Component comp)
Removes the specified component from the container. void setDefaultCloseOperation(int operation)
Sets the operation that will happen by default when the user initiates a "close" on this frame. You must specify one of the following choices:
DO_NOTHING_ON_CLOSE (defined in WindowConstants): Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
The value is set to HIDE_ON_CLOSE by default.
JFrame Cont`
Beberapa method: void add(Component comp)
Adds the specified component into the container. void remove(Component comp)
Removes the specified component from the container.
void setTitle(String title)Sets the title for this frame to the specified string.
void setDefaultCloseOperation(int operation)Sets the operation that will happen by default when the user initiates a "close" on this frame.
JFrame Cont`
Default close operation yang ada: DO_NOTHING_ON_CLOSE (defined in WindowConstants):
Don't do anything; require the program to handle the operation in the windowClosing method of a registered WindowListener object.
HIDE_ON_CLOSE (defined in WindowConstants): Automatically hide the frame after invoking any registered WindowListener objects.
DISPOSE_ON_CLOSE (defined in WindowConstants): Automatically hide and dispose the frame after invoking any registered WindowListener objects.
EXIT_ON_CLOSE (defined in JFrame): Exit the application using the System exit method. Use this only in applications.
The value is set to HIDE_ON_CLOSE by default.
JTextField
Digunakan untuk tempat inputan text dari user
Beberapa constructor:JTextField()
Constructs a new TextField.JTextField(String text)
Constructs a new TextField initialized with the specified text.
JTextField Cont`
Beberapa method: void setText(String t)
Sets the text of this TextComponent to the specified text.
String getText() Returns the text contained in this TextComponent.
void setEditable(boolean e) Sets the specified boolean to indicate whether or not this
TextComponent should be editable.
boolean isEditable() Returns the boolean indicating whether this TextComponent
is editable or not.
JPasswordField
Digunakan untuk tempat inputan password dari user
Beberapa constructor:JPasswordField()
Constructs a new JPasswordField.JPasswordField(String text)
Constructs a new JPasswordField initialized with the specified text.
JPasswordField Cont`
Beberapa method: void setText(String t)
Sets the text of this JPasswordField to the specified text. char[] getPassword()
Returns the text contained in this JPasswordField. void setEditable(boolean e)
Sets the specified boolean to indicate whether or not this JPasswordField should be editable.
boolean isEditable() Returns the boolean indicating whether this JPasswordField is
editable or not. void setEchoChar(char c)
Sets the echo character for this JPasswordField. char getEchoChar()
Returns the character to be used for echoing.
JLabel
Digunakan untuk labelingBeberapa constructor:
JLabel()Constructs a new JLabel.
JLabel(String text)Constructs a new JLabel initialized with the specified text.
JLabel Cont`
Beberapa method: void setText(String text)
Defines the single line of text this component will display. String getText()
Returns the text string that the label displays. void setLabelFor(Component c)
Set the component this is labelling. Component getLabelFor()
Get the component this is labelling. void setDisplayedMnemonic(char aChar)
Specifies the displayedMnemonic as a char value. int getDisplayedMnemonic()
Return the keycode that indicates a mnemonic key.
JButton
Ya tombolBeberapa constructor:
JButton() Creates a button with no set text or icon.
JButton(String text) Creates a button with text.
JButton Cont`
Ya tombol Beberapa constructor:
JButton() Creates a button with no set text or icon.
JButton(String text) Creates a button with text.
Beberapa method: void setMnemonic(char mnemonic)
Set the mnemonic for a button. int getMnemonic()
Returns the keyboard mnemonic from the the current model.
Several Common Methods
void setVisible(boolean aFlag)Makes the component visible or invisible.
boolean isVisible() Check if the component is visible or invisible.
void setEnabled(boolean enabled) Sets whether or not this component is enabled.
boolean isVisible() Check if the component is enabled.
void setToolTipText(String text) Registers the text to display in a tool tip. The text displays when
the cursor lingers over the component. String getToolTipText()
Returns the tooltip string that has been set with setToolTipText.
Several Common Methods Cont`
void setLocation(int x, int y)Moves this component to a new location. The top-left corner of
the new location is specified by the x and y parameters in the coordinate space of this component's parent.
void setBounds(int x, int y, int width, int height)Moves and resizes this component. The new location of the top-
left corner is specified by x and y, and the new size is specified by width and height.
void setSize(int width, int height) Resizes this component so that it has width width and height
height.
Layout Manager
Untuk mengatur lokasi komponen di dalam sebuah container
Beberapa Layout yang sering digunakan:BorderLayoutBoxLayoutCardLayoutFlowLayoutNo Layout
BorderLayout
http://download.oracle.com/javase/tutorial/uiswing/layout/border.html
BorderLayout membagi area menjadi 5 bagian yang dispesifikasi berdasar 5 konstanta berikut: PAGE_START, PAGE_END, LINE_START, LINE_END, CENTER
BoxLayout
http://download.oracle.com/javase/tutorial/uiswing/layout/box.html
BoxLayout akan menyusun komponen secara menurun atau mendatar berdasarkan konstanta berikut: PAGE_AXIS (menurun), LINE_AXIS (mendatar)
CardLayout
http://download.oracle.com/javase/tutorial/uiswing/layout/card.html
CardLayout digunakan untuk mengatur tampilan dari komponen yang menempati tempat yang sama namun syarat tampil berbeda sama seperti halnya tumpukan kartu.
Menempati tempat yang sama namun tampil berdasarkan combobox di atas
FlowLayout
http://download.oracle.com/javase/tutorial/uiswing/layout/flow.html
FlowLayout akan menyusun komponen secara mendatar.
No Layout
http://download.oracle.com/javase/tutorial/uiswing/layout/none.html
No Layout berarti tidak ada layout yang digunakan. Programmer dapat menyusun sendiri lokasi dan ukuran komponen yang ditempelkan pada container.
Sample Code
package gui;
import java.awt.Dimension;import java.awt.Toolkit;
import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPasswordField;import javax.swing.JTextField;
public class Gui {
public static void main(String[] args) {Dimension screenSize =
Toolkit.getDefaultToolkit().getScreenSize();
Sample Code Cont`
JFrame jFrame = new JFrame();jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);jFrame.setLayout(null);jFrame.setSize(300, 160);jFrame.setLocation(
(int) ((screenSize.getWidth() - jFrame.getWidth()) / 2),(int) ((screenSize.getHeight() - jFrame.getHeight()) / 2));
jFrame.setTitle("User Login");
JTextField jTfUsn = new JTextField();jTfUsn.setBounds(110, 20, 160, 24);
JLabel jLUsn = new JLabel();jLUsn.setBounds(20, 24, 80, 16);jLUsn.setDisplayedMnemonic('u');
jLUsn.setLabelFor(jTfUsn);jLUsn.setText("Username");
Sample Code Cont`
JPasswordField jPfPwd = new JPasswordField();jPfPwd.setBounds(110, 50, 160, 24);
JLabel jLPwd = new JLabel();jLPwd.setBounds(20, 54, 80, 16);jLPwd.setDisplayedMnemonic('p');jLPwd.setLabelFor(jPfPwd);jLPwd.setText("Password");
JButton jBLogin = new JButton();jBLogin.setBounds((int) ((jFrame.getWidth() - 80) / 2),
jFrame.getHeight() - 80, 80, 30);jBLogin.setMnemonic('l');jBLogin.setText("Login");
Sample Code Cont`
jFrame.add(jLUsn);
jFrame.add(jTfUsn);
jFrame.add(jLPwd);
jFrame.add(jPfPwd);
jFrame.add(jBLogin);
jFrame.setVisible(true);
}
}
Event Handling
Every time the user types a character (KeyEvent) or pushes a mouse button( MouseEvent), an event occurs.
Any object can be notified of the event. implement the appropriate interface andbe registered as an event listener on the
appropriate event source.Swing components can generate many
kinds of events.
Example GUI Handling
Act that results in the event Listener type User clicks a button,
presses Return while typing in a ActionListener
text field, or chooses a menu item User closes a frame (main window) WindowListener User presses a mouse button
while the cursor is over a component MouseListener User moves the mouse over a component MouseMotionListener Component becomes visible ComponentListener Component gets the keyboard focus FocusListener Table or list selection changes ListSelectionListener
How to Handling Event
Implement and instantiate an event Listener : public class MyClass implements XXXListener { …} XXXListener l = (XXXListener) new MyClass(…);
Register the eventListener as an listener on event source: aEventSource.addXXXListener( l ) ;
From now on, every time an event e occurs, the event source object will call the appropriate doXXXAction(e) from l.
Example
…final JFrame jFrame = new JFrame();…final JTextField jTfUsn = new JTextField();…final JPasswordField jPfPwd = new JPasswordField();…jBLogin.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {JOptionPane.showMessageDialog(jFrame, "Username: " + jTfUsn.getText()
+ " Password: " + new String(jPfPwd.getPassword()));}
});…
Example - Output
Reference
Java DocJava GUI Lecture - Cheng-Chia Chen