Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pemrograman Berorientasi Objek Bab 7 – GUI Programming.

Similar presentations


Presentation on theme: "Pemrograman Berorientasi Objek Bab 7 – GUI Programming."— Presentation transcript:

1 Pemrograman Berorientasi Objek Bab 7 – GUI Programming

2 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)

3 Look At These! Dari kedua app di atas, app manakah yang lebih Anda sukai untuk Anda gunakan? Manakah yang lebih menarik?

4 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

5 GUI Components A Form A Label A Text Field A Password Field A Button

6 GUI Component Category Komponen GUI dibagi ke dalam 2 kelompok kategori: Container Containment

7 Container Container adalah component yang mampu menampung komponen lain dan merupakan wadah untuk meletakkan containment component Misalkan form, panel

8 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

9 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

10 Swing Teach Swing Why not AWT? App yang dibangun menggunakan AWT sering mengalami inconsistent dalam hal tampilan jika dijalankan di platform yang berbeda

11 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.

12 Top-Level Containers Frame ( and JFrame) Dialog ( and JDialog) Applet (and JApplet)

13 General-Purpose Containers Panel ( and JPanel) JToolBar JScrollPane JTabbedPane JSplitPane

14 Special-Purpose Containers JLayeredPane JInternalFrames Root Pane

15 Basic Controls JCheckBox JRadioButton JButton JMenu JMenuItem List ( and JList) Choice ( and JComboBox) JTextField JSlider

16 Uneditable Information Displays Label ( and JLabel) JProgressBar JToolTip

17 Editable Displays of Formatted Information JTree JTextJTable FileDialog ( and JFileChooser) JColorChooser

18 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

19 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:

20 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 OptionshowConfirmDialogComponent Object 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 parametershowConfirmDialogComponent ObjectString 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.showConfirmDialogComponent ObjectString 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.showConfirmDialogComponent ObjectStringIcon

21 JOptionPane Cont` static String showInputDialog(Component parentComponent, Object message) Shows a question-message dialog requesting input from the user parented to parentComponent.StringshowInputDialogComponentObject static String showInputDialog(Component parentComponent, Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user and parented to parentComponent.StringshowInputDialogComponentObject 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.StringshowInputDialogComponentObject String 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.ObjectshowInputDialogComponentObject StringIconObject static String showInputDialog(Object message) Shows a question-message dialog requesting input from the user.StringshowInputDialogObject static String showInputDialog(Object message, Object initialSelectionValue) Shows a question-message dialog requesting input from the user, with the input value initialized to initialSelectionValue.StringshowInputDialogObject

22 JOptionPane Cont` static void showMessageDialog(Component parentComponent, Object message) Brings up an information-message dialog titled "Message".showMessageDialogComponent Object 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.showMessageDialogComponent ObjectString static void showMessageDialog(Component parentComponent, Object message, String title, int messageType, Icon icon) Brings up a dialog displaying a message, specifying all parameters.showMessageDialogComponent ObjectStringIcon 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.showOptionDialogComponent ObjectString IconObject

23 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. message A descriptive message to be placed in the dialog box. In the most common usage, message is just a String or String constant. messageType Defines the style of the message. The possible values are: ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, QUESTION_MESSAGE, PLAIN_MESSAGE optionType Defines 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

24 JOptionPane Cont` options A 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: Component The component is added to the button row directly. Icon A JButton is created with this as its label. other The Object is converted to a string using its toString method and the result is used to label a JButton.

25 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).

26 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

27 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 JFrame(String title) Creates a new, initially invisible Frame with the specified title. JFrameString

28 JFrame Cont` Beberapa method: void remove(Component comp) Removes the specified component from the container.removeComponent 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:setDefaultCloseOperation 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.

29 JFrame Cont` Beberapa method: void add(Component comp) Adds the specified component into the container.addComponent void remove(Component comp) Removes the specified component from the container.removeComponent void setTitle(String title) Sets the title for this frame to the specified string.setTitleString void setDefaultCloseOperation(int operation) Sets the operation that will happen by default when the user initiates a "close" on this frame.setDefaultCloseOperation

30 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.

31 JTextField Digunakan untuk tempat inputan text dari user Beberapa constructor: JTextField() Constructs a new TextField. JTextField JTextField(String text) Constructs a new TextField initialized with the specified text. JTextFieldString

32 JTextField Cont` Beberapa method: void setText(String t)String Sets the text of this TextComponent to the specified text. String getText() String 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.

33 JPasswordField Digunakan untuk tempat inputan password dari user Beberapa constructor: JPasswordField() Constructs a new JPasswordField. JPasswordField JPasswordField(String text) Constructs a new JPasswordField initialized with the specified text. JPasswordFieldString

34 JPasswordField Cont` Beberapa method: void setText(String t)String Sets the text of this JPasswordField to the specified text. char[] getPassword() char[] 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.setEchoChar char getEchoChar() Returns the character to be used for echoing.getEchoChar

35 JLabel Digunakan untuk labeling Beberapa constructor: JLabel() Constructs a new JLabel. JLabel JLabel(String text) Constructs a new JLabel initialized with the specified text. JLabelString

36 JLabel Cont` Beberapa method: void setText(String text) Defines the single line of text this component will display.setTextString String getText() Returns the text string that the label displays. StringgetText void setLabelFor(Component c) Set the component this is labelling.setLabelForComponent Component getLabelFor() Get the component this is labelling. ComponentgetLabelFor void setDisplayedMnemonic(char aChar) Specifies the displayedMnemonic as a char value.setDisplayedMnemonic int getDisplayedMnemonic() Return the keycode that indicates a mnemonic key.getDisplayedMnemonic

37 JButton Ya tombol Beberapa constructor: JButton() Creates a button with no set text or icon. JButton JButton(String text) Creates a button with text. JButtonString

38 JButton Cont` Ya tombol Beberapa constructor: JButton() Creates a button with no set text or icon. JButton JButton(String text) Creates a button with text. JButtonString Beberapa method: void setMnemonic(char mnemonic) Set the mnemonic for a button.setMnemonic int getMnemonic() Returns the keyboard mnemonic from the the current model.getMnemonic

39 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)String Registers the text to display in a tool tip. The text displays when the cursor lingers over the component. String getToolTipText() String Returns the tooltip string that has been set with setToolTipText.

40 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.

41 Layout Manager Untuk mengatur lokasi komponen di dalam sebuah container Beberapa Layout yang sering digunakan: BorderLayout BoxLayout CardLayout FlowLayout No Layout

42 BorderLayout BorderLayout membagi area menjadi 5 bagian yang dispesifikasi berdasar 5 konstanta berikut: PAGE_START, PAGE_END, LINE_START, LINE_END, CENTER

43 BoxLayout BoxLayout akan menyusun komponen secara menurun atau mendatar berdasarkan konstanta berikut: PAGE_AXIS (menurun), LINE_AXIS (mendatar)

44 CardLayout 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

45 FlowLayout FlowLayout akan menyusun komponen secara mendatar.

46 No Layout No Layout berarti tidak ada layout yang digunakan. Programmer dapat menyusun sendiri lokasi dan ukuran komponen yang ditempelkan pada container.

47 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();

48 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");

49 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");

50 Sample Code Cont` jFrame.add(jLUsn); jFrame.add(jTfUsn); jFrame.add(jLPwd); jFrame.add(jPfPwd); jFrame.add(jBLogin); jFrame.setVisible(true); }

51 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 and be registered as an event listener on the appropriate event source. Swing components can generate many kinds of events.

52 Example GUI Handling Act that results in the event Listener type User clicks a button, presses Return while typing in aActionListener 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

53 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.

54 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())); } }); …

55 Example - Output

56 Reference Java Doc Java GUI Lecture - Cheng-Chia Chen


Download ppt "Pemrograman Berorientasi Objek Bab 7 – GUI Programming."

Similar presentations


Ads by Google