1 / 98

GUI Programming

GUI Programming. graphical user interface human-computer interface replaces command-line interface interface builders Java AWT/Swing behavior is platform independent event-driven programming user in control user actions  events program responds to events. AWT and Swing.

mona-ortiz
Download Presentation

GUI Programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. GUI Programming • graphical user interface • human-computer interface • replaces command-line interface • interface builders • Java AWT/Swing • behavior is platform independent • event-driven programming • user in control • user actions  events • program responds to events

  2. AWT and Swing • AWT components are heavyweight • associated with native components created by the underlying window system • appearance determined by the window system • different platforms = different look • Swing components are lightweight • created by the JVM • appearance determined by the JVM • different platforms = same look • Composite design pattern

  3. AWT classes Component Button Container Canvas Checkbox Panel Window ScrollPane Choice Label Frame Dialog List Scrollbar TextComponent TextField TextArea

  4. Swing classes Component Container JComponent JButton JCombobox JPanel Window JCheckbox JLabel Frame Dialog JList JScrollbar JFrame JDialog JTextComponent JTextField JTextArea JWindow

  5. Component • abstract class • methods • paint(Graphics g) • repaint() calls paint • setSize(int width, int height) • setVisible(boolean b) • requestFocus() • validate()

  6. Container • abstract class • widget containers • can contain containers • layout • LayoutManager • methods • add(Component comp) • add(String name, Component comp) • remove(Component comp) • removeAll() • setLayout(LayoutManager mgr) • paint(Graphics g) // from Component should be overridden in order to draw all components of the container

  7. JComponent • Swing version of Component • abstract class • adds additional functionality • new methods • Dimension getPreferredSize() • Dimension getSize(Dimension rv) • setPreferredSize(Dimension preferredSize) • setEnabled(boolean enabled)

  8. JFrame • top level window • components • menu bar • content pane • all layout etc. • constructors • JFrame() • JFrame(String title) • methods • Container getContentPane() • dispose() // from Window • pack() // from Window • setJMenuBar(JMenuBar menuBar) • setResizable(boolean b) // from Frame • setTitle(String title) // from Frame • setDefaultCloseOperation(int operation)

  9. Layout managers • each container has a layout manager • handles the layout of the components contained in the container setLayout(lm) sets lm as the layout manager of this container Container LayoutManager BorderLayout CardLayout FlowLayout GridLayout

  10. Layout managers • BorderLayout manager can manage five components, • default layout manager for Frame, JFrame • locations: North, East, South, West, Center add(“North“, new Jbutton(“Button 1“); • GridLayout manager creates a rectangular array of components • each component occupies the same size portion of the screen new GridLayout(4,4,3,3) • FlowLayout manager places components in rows left to right, top to bottom • components need not to have the same size • default manager for Panel • CardLayout manager stacks components vertically • only one component is visible at one time • components can be named CardLayout lm = new CardLayout(); Panel p = new Panel(lm); p.add(“One“, new Label(“Number One“)); lm.show(p,“One“);

  11. Reaction Model • reactive • react to event as soon as it happens • usually for buttons and menu selections • write Listener and handle event • used when view must change immediately • completed data entry • doing input validation • reactive selections • passive • don’t react to event when it happens • wait until significant event (e.g. button press) • access widget to get its state/contents • usually for information entry • text boxes • selections

  12. Events • caused by user actions • event objects • represent particular events • carry further information • event source objects • register listeners • send listeners events • GUI widgets • listeners • receive/handle events • listener interfaces

  13. Example - ActionEvent • button presses cause ActionEvents • ActionListeners handle ActionEvents • actionPerformed • getActionCommand • JButton • constructor • addActionListener • setActionCommand • creating a button on the fly JButton button = new JButton("Button"); button.addActionListener(new ActionListener() { public void actionPerformed (ActionEvent e) { //do something }});

  14. Example (cont.) • using a private listener class JButton button = new JButton("Button"); button.addActionListener(new MyActionListener()); private class MyActionListener implements ActionListener public void actionPerformed (ActionEvent e) { //do something } }

  15. Example (cont.) • combining the button and the listener in a new class JButton button = new MyButton(); private class MyButton extends JButton implements ActionListener { public MyButton() { super("Button"); addActionListener(this); } public void actionPerformed (ActionEvent e) { //do something } }

  16. Example (cont.) • a button to make a window invisible private class MyOKButton extends JButton implements ActionListener { private JDialog parent; public MyOKButton(JDialog parent) { super("Ok"); this.parent = parent; addActionListener(this); } public void actionPerformed (ActionEvent e) { parent.setVisible(false); } }

  17. Example (cont.) • generic ButtonAdapter class abstract class ButtonAdapter extends JButton implements ActionListener { public ButtonAdapter(String name) { super(name); addActionListener(this); } public void actionPerformed(ActionEvent e) { pressed(); } public abstract void pressed(); }

  18. Listeners / Events /Adapters • KeyEvent • MouseEvent • MouseWheelEvent • WindowEvent • ComponentEvent • ContainerEvent • adapter classes • KeyAdapter • MouseAdapter • MouseMotionAdapter • MouseInputAdapter • WindowAdapter • ComponentAdapter • ContainerAdapter • listener classes • ActionListener • ItemListener • ListSelectionListener • AdjustmentListener • KeyListener • MouseListener • MouseWheelListener • WindowListener • ComponentListener • ContainerListener • event classes • ActionEvent • ItemEvent • ListSelectionEvent • AdjustmentEvent

  19. Event Hierarchy • semantic events • ActionEvent • button click (incl. checkbox and radio button), menu selection combo box selection, enter in text area • ItemEvent • change of the state of an item, e.g., checkbox and radio box • ListSelectionEvent • list selections • AdjustmentEvent • scroll bar changes • low level events • KeyEvent • MouseEvent • MouseWheelEvent • WindowEvent

  20. Listeners (cont.) • handling window closing • JFrame • top level window • window events • WindowListener • windowClosing addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); dispose(); System.exit(0); }}); • WindowAdapter • null methods

  21. Listeners (cont.) private class MyMouseListener extends MouseAdapter { public void mouseClicked (MouseEvent me) { int x = me.getX(); int y = me.getY(); if (me.getButton() == MouseEvent.BUTTON1) { // action for left mouse button }; if (me.getButton() == MouseEvent.BUTTON2) { // action for middle mouse button }; if (me.getButton() == MouseEvent.BUTTON3) { // action for right mouse button }; } }

  22. JPanel • contained container • lightweight • typically used as top level container in content pane • also for controlling layout • default layout manager: FlowLayoutManager • constructor • JPanel()

  23. JButton • button widget • button with label • press generates ActionEvent • constructor • JButton ( String label ) • methods • addActionListener ( ActionListener l ) • setActionCommand ( String actionCommand ) • setEnabled ( boolean b ) • setText ( String text )

  24. JMenuBar • associated with a JFrame • frame.setJMenuBar ( JMenuBar mBar ) • constructor • JMenuBar ( ) • methods • add ( JMenu menu )

  25. JMenu • menu in a JMenuBar • constructor • JMenu ( String label ) • methods • add ( JMenuItem item ) • addSeparator ( ) • insert ( JMenuItem item, int pos) • insertSeparator ( int pos ) • remove ( JMenuItem item ) • remove ( int pos ) • removeAll ( )

  26. JMenuItem • selectable item in a JMenu • constructors • JMenuItem ( String text ) • methods • addActionListener ( ActionListener listener ) • setActionCommand ( String command ) • setEnabled ( boolean b )

  27. Example public MyFrame() { JMenuBar myBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); JMenuItem startItem = new JMenuItem("Start Game"); startItem.setEnabled(false); fileMenu.add(startItem); JMenuItem quitItem = new JMenuItem("Quit"); quitItem.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { System.exit(0); }}); fileMenu.add(quitItem); myBar.add(fileMenu); setJMenuBar(myBar); setSize(500,300); setLocation(200,200); setVisible(true); }

  28. JRadioButton • buttons that can be grouped • ButtonGroup • constructor • ButtonGroup ( ) • methods • add ( AbstractButton b ) • ButtonModel getSelection ( ) • constructors • JRadioButton ( String label ) • JRadioButton ( String label, boolean state ) • methods • addActionListener ( Actionlistener listener ) • setActionCommand ( String actionCommand ) • setEnabled ( boolean b ) • boolean isSelected ( ) • setSelected ( boolean state )

  29. JDialog • dialog window • has a parent (owner) • modal or non-modal • content pane • constructors • JDialog ( ) • JDialog ( Dialog owner ) • JDialog ( Frame owner ) • JDialog ( Dialog owner, boolean modal ) • JDialog ( Frame owner, boolean modal ) • methods • Container getContentPane ( ) • dispose ( ) // from Window • pack ( ) // from Window • setResizable ( boolean b ) // from Dialog • setTitle ( String title ) // from Dialog • setDefaultCloseOperation ( int operation )

  30. Example public MyDialog(JFrame parent) { super(parent,true); setSize(220,160); setTitle("Select number of players"); ButtonGroup group = new ButtonGroup(); JRadioButton one = new JRadioButton("One",true); JRadioButton two = new JRadioButton("Two",false); JRadioButton three = new JRadioButton("Three",false); JRadioButton four = new JRadioButton("Four",false); group.add(one); group.add(two); group.add(three); group.add(four); JPanel selectPanel = new JPanel(); selectPanel.setLayout(new GridLayout(4,1)); selectPanel.add(one); selectPanel.add(two); selectPanel.add(three); selectPanel.add(four); getContentPane().add(selectPanel,BorderLayout.NORTH);

  31. Example (cont’d) JPanel buttonPanel = new JPanel(); JButton ok = new JButton("OK"); ok.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { setVisible(false); }}); buttonPanel.add(ok,BorderLayout.CENTER); getContentPane().add(buttonPanel,BorderLayout.SOUTH); setVisible(false); } In MyFrame: private MyDialog dialog = new MyDialog(this); ... startItem.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent e) { dialog.setVisible(true); }});

  32. JScrollBar • constructors • JScrollBar (int orientation, int value, int extent, int min, int max ) • methods • addAdjustmentListener( AdjustmentListener listener ) • getOrientation( ) • getValue( ) • setValue( int value )

  33. JLabel • text label • constructors • JLabel ( String text ) • JLabel ( String text, int align ) • JLabel ( Icon icon ) • JLabel ( String text, Icon icon, int align ) • alignment • JLabel.LEFT • JLabel.RIGHT • JLabel.CENTER • methods • setText ( String text ) • setIcon ( Icon icon )

  34. Example private JLabel widthLabel = new JLabel(" Width: 5000"); private JLabel heightLabel = new JLabel(" Height: 5000"); private JScrollBar widthScrollbar = new JScrollBar(JScrollBar.HORIZONTAL,5000,0,0,32000); private JScrollBar heightScrollbar = new JScrollBar(JScrollBar.HORIZONTAL,5000,0,0,32000); widthScrollbar.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { widthLabel.setText(" Width: " + widthScrollbar.getValue()); }}); heightScrollbar.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { heightLabel.setText(" Height: " + heightScrollbar.getValue()); }});

  35. JOptionPane • easy pop-up of standard dialogs • modal • methods (static) • int showMessageDialog ( Component parent, Object msg) • int showMessageDialog ( Component parent, Object msg, String title, int type ) • int showOptionDialog ( … ) • int showConfirmDialog ( … ) • String showInputDialog ( … )

  36. JFileChooser • file selection dialog • can specify subdirectory and file filter • constructor • JFileChooser ( ) • JFileChooser ( File currentDirectory ) • methods • File getSelectedFile • setCurrentDirectory ( File dir ) • setFileFilter ( FileFilter filter ) • showOpenDialog ( Component Parent ) • showSaveDialog ( Component Parent )

  37. JTextComponent • text entry areas • new lines (\n) • JTextField • editable single-line text • JTextField ( int cols ) • JTextArea • editable multi-line text • JTextArea ( int rows, int cols ) • methods • setText ( String text ) • String getText ( ) • setEditable ( boolean b ) • JPasswordField • setEchoChar ( char echo ) • char [ ] getPassword ( )

  38. JCheckbox • a checkbox • generates ActionEvent • constructors • JCheckbox ( String label ) • JCheckbox ( String label, boolean state ) • methods • addActionListener ( Actoinlistener listener ) • setActionCommand ( String actionCommand ) • setEnabled ( boolean b ) • boolean isSelected ( ) • setSelected ( boolean state )

  39. JList • list selector • generates ListSelectionEvent • constructor • JList ( Object[] items ) • JList ( ListModel dataModel ) • methods • setVisibleRowCount ( int rows ) • setFixedCellWidth ( int width) • setSelectionMode ( int mode ) • JList.SINGLE_SELECTION, JList.SINGLE_INTERVAL_SELECTION, JList.MULTIPLE_INTERVAL_SELECTION • addListSelectionListener ( ListSelectionListener l ) • Object[] getSelectedValues ( ) • Object getSelectedValue ( )

  40. ListSelectionListener • javax.swing.event • method • valueChanged ( ListSelectionEvent e ) • ListSelectionEvent • boolean getValueIsAdjusting ( ) • Object getSource ( )

  41. JScrollPane • scrolling for other components • place component in JScrollPane and then add scroll pane to container • constructor • JScrollPane ( Component c )

  42. 2D Graphics and Animation Requirements: Java 1.4.1 or newer. Some basic notions: • Resolution: Typical resolutions are 640x480, 800x600, 1024x768 and 1280x1024. • Bit depth: The number of colors a monitor can display depends on the bit depth. Common bit depth are 8, 15, 16, 24 and 32 bits. • human eye can see about 10 million colors  16,777,216 = 224, 24-bit is optimal. • Refresh rate: The monitor continuously refreshes the display. How fast it refreshes is known as the refresh rate, and is measured in Hertz (Hz), i.e., cycles per second. A refresh rate between 75Hz and 85Hz is usually suitable for the human eye.

  43. Images - Transparency Three types of image transparency: • Opaque: Every pixel in the image is visible. • Transparent: Every pixel in the image is either completely visible or completely see-through. • Translucent: Pixels can be partially transparent, to create a ghostlike, partially see-through effect.

  44. Images – File Formats Three formats are supported: • GIF: • opaque or transparent • 8-bit color or less • PNG: • any type of transparency • up to 24-bit color • PNG supercedes GIF • JPEG: • opaque • 24-bit color • high compression (lossy compression) • for photographic images

  45. Images – Reading Using the Toolkit’s getImage() method: Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = toolkit.getImage(filename); The code above does not actually load the image (The image begins loading in another thread). ImageIcon icon = new ImageIcon(filename); Image image = icon.getImage(); or ImageIO.read(new File(filename));

  46. Hardware-Accelerated Images Hardware-accelerated images are images that are stored in video memory rather than system memory. Java tries to hardware-accelerate any image you load. Issues that will keep images from being accelerated: • constantly changing the contents of the image • translucent images are not accelerated (Java 1.4.1) • system has no accelerated images capability

  47. Benchmark The differences in speed are: System: • Program ImageSpeedTest.java (Listing 2.4) • 600MHz Athlon • GeForce-256 video card • display resolution 800x600 • bit depth: 16 Result: • Opaque: 5550.599 images/sec • Transparent: 5478.6953 images/sec • Translucent: 85.2197 images/sec • Translucent (Anti-Aliased): 113.18243 images/sec

  48. Animation Animation = Displaying a sequence of images Images Image A Image B Image C Image B Time (milliseconds) 0ms 200ms 275ms 300ms

  49. import java.awt.Image; import java.util.ArrayList; /** The Animation class manages a series of images (frames) and the amount of time to display each frame. */ public class Animation { private List<Pair<Image,Long>> frames; private int currFrameIndex; private long animTime; private long totalDuration; private boolean repeating; private boolean running; /** Creates a new, empty Animation. */ public Animation(boolean repeating) { frames = new ArrayList<Pair<Image,Long>>(); totalDuration = 0; this.repeating = repeating; running = false; }

  50. /** Adds an image to the animation with the specified duration (time to display the image). */ public synchronized void addFrame(Image image, long duration) { totalDuration += duration; frames.add(new Pair<Image,Long>(image, totalDuration)); } /** Starts this animation over from the beginning. */ public synchronized void start() { reset(); running = true; } public synchronized void reset() { animTime = 0; currFrameIndex = 0; }

More Related