Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:

Similar presentations


Presentation on theme: "CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:"— Presentation transcript:

1 CS102 – GUI Based on : David Davenport’s slides Spring 2002 References: http://java.sun.com/docs/books/tutorial/uiswing http://www.aduni.org/courses/java Core Java Volume 1 http://www.javaworld.com/javaworld/jw-04-1998/jw-04-howto.html

2 Swing is implemented without making use of native window elements components are painted by java on blank windows. more flexibility, not the lowest common denominator same look, same bugs in all platforms The Swing components will continue to be enhanced in the future, AWT is dying

3 Programming forms F Procedural programming F code is executed in sequential order. F Event-driven programming F code is executed upon activation of events. statement 1 statement 2 statement 3 -------- statement n method 1 method 2 method 3 -------- method n Do method 1 then method 3 Do method 2 then method 1 then method 3

4 procedural programming Up to now, our control flow model has been pretty straight-forward. Execution starts at main() and executes statement sequentially branching with if,for,and while statement, and occasional method calls. When we need user input we call read() on the console stream which waits (blocks) until the user types something, then returns. One problem with this model is: How do we wait for and respond to input from more than one source (eg keyboard and mouse). If we block on either waiting for input, we may miss input from the other.

5 Event-driven programming the system waits for user input events, and these events trigger program methods Event-based programming addresses the two problems: How to wait on multiple input sources (input events) How to decide what to do on each type of input event

6 General form of event- driven programming The operating system and window system process input event from devices (mouse movement, mouse clicks, key presses etc) The window system decides which window, and hence which frame and program, each input event belongs to. A data structure describing the event is produced and placed on an 'event queue'. Events are added to one end of the queue by the window system. Events are removed from the queue and processed by the program. These event data structures hold information including: Which of the program's windows this event belongs to. The type of event (mouse click, key press, etc.) Any event-specific data (mouse position, key code, etc.)

7 Event loop main(){...set up application data structures......set up GUI.... // enter event loop while(true){ Event e = get_event(); process_event(e); // event dispatch routine } } the event loop is usually hidden from programmer, he/she provides just a process_event() method

8 AWT Applications - Frame Frame is a container for components Frame with normal window controls Optional Menu Three containers in Frame with Border Layout UI-components inside containers each with own layout

9 Understanding the GUI UI-containers have list of UI-components Each UI-component is a class with paint method & lists of Event listeners {Frame} {label} {textfield} {button} components

10 Setting up the GUI Extend Frame class In constructor Create instances of containers & add them to Frame Create instances of components & add them to containers or Frame Possibly override paint method UI-components added to components list Painting Frame 1. paints Frame borders 2. calls Frame paint method 3. calls paint method of each object in component list Hint: Employ layout managers to arrange components in containers

11 A simple example import javax.swing.*; class FirstFrame extends JFrame { public FirstFrame() { setTitle("FirstFrame"); setSize(300, 200); } public class FirstTest { public static void main(String[] args) { JFrame frame = new FirstFrame(); frame.show(); }

12 Simple Example Remarks we have two classes, one for the frame, the other for the main method that creates the frame we could have put the main method inside class FirstFrame if we don’t set the size, the default is a window of size 0x0 java runtime creates a new thread for our frame it doesn’t terminate, just hides

13 Hello World Program import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { JFrame frame = new JFrame("HelloWorld"); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setBounds(200, 200, 200, 50); frame.setVisible(true); }

14 Containers Swing provides three generally useful top-level container classes: JFrame, JDialog, and JApplet.JFrameJDialogJApplet To appear onscreen, every GUI component must be part of a containment hierarchy. Each containment hierarchy has a top-level container as its root. Each top-level container has a content pane that, generally speaking, contains the visible components in that top-level container's GUI. You can optionally add a menu bar to a top-level container. The menu bar is positioned within the top-level container, but outside the content pane.

15 Container Tree a frame, or main window (JFrame) a panel, sometimes called a pane (JPanel) a button (JButton) a label (JLabel)

16 Containers.. The frame is a top-level container. It exists mainly to provide a place for other Swing components to paint themselves. The panel is an intermediate container. Its only purpose is to simplify the positioning of the button and label. Other intermediate Swing containers, such as scroll panes (JScrollPane) and tabbed panes (JTabbedPane), typically play a more visible, interactive role in a program's GUI. The button and label are atomic components -- components that exist not to hold random Swing components, but as self-sufficient entities that present bits of information to the user. Often, atomic components also get input from the user.

17 Layouts

18 Using Layout Managers By default, every container has a layout manager. All JPanel objects use a FlowLayout by default, whereas content panes (the main containers in JApplet, JDialog, and JFrame objects) use BorderLayout by default. You can change the layout as: JPanel pane = new JPanel(); pane.setLayout(new BorderLayout()); When you add components to a panel or a content pane, the arguments you specify to the add method depend on the layout manager that the panel or content pane is using.

19 Border Layout A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center. Each region may contain no more than one component, and is identified by a corresponding constant: NORTH, SOUTH, EAST, WEST, and CENTER. When adding a component to a container with a border layout, use one of these five constants, for example: Panel p = new Panel(); p.setLayout(new BorderLayout()); p.add(new Button("Okay"), BorderLayout.SOUTH);

20 Border Layout Example Container contentPane = getContentPane(); //Use the content pane's default BorderLayout. //contentPane.setLayout(new BorderLayout()); contentPane.add(new JButton("Button 1 (NORTH)"), BorderLayout.NORTH); contentPane.add(new JButton("2 (CENTER)"), BorderLayout.CENTER); contentPane.add(new JButton("Button 3 (WEST)"), BorderLayout.WEST); contentPane.add(new JButton("Long-Named Button 4 (SOUTH)"), BorderLayout.SOUTH); contentPane.add(new JButton("Button 5 (EAST)"), BorderLayout.EAST);

21 Border Layout Output

22 Border Layout cont. We specified the component as the first argument to the add method. For example: add(component, BorderLayout.CENTER) //preferred However, you might see code in other programs that specifies the component second. For example, the following are alternate ways of writing the preceding code: add(BorderLayout.CENTER, component) add("Center", component) //valid but error prone By default, a BorderLayout puts no gap between the components it manages. You can specify gaps (in pixels) using the following constructor: BorderLayout(int horizontalGap, int verticalGap) You can also use the following methods to set the horizontal and vertical gaps, respectively: void setHgap(int) void setVgap(int)

23 BorderLayout(20, 20)

24 Border Layout Resizing First North and South are drawn with their normal sizes, then east & west, finally all the rest of the space is reserved for center. center is the default location by default anything in center fill resize to fill the space

25 Border Layout Resized

26 Flow Layout FlowLayout puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, FlowLayout uses multiple rows. Within each row, components are centered (the default), left-aligned, or right-aligned as specified when the FlowLayout is created.

27 Flow Layout Example Container contentPane = getContentPane(); contentPane.setLayout(new FlowLayout()); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5"));

28 Flow Layout Example Output

29 The FlowLayout API The FlowLayout class has three constructors: public FlowLayout() public FlowLayout(int alignment) public FlowLayout(int alignment, int horizontalGap, int verticalGap) The alignment argument must have the value FlowLayout.LEFT, FlowLayout.CENTER, or FlowLayout.RIGHT. The horizontalGap and verticalGap arguments specify the number of pixels to put between components. If you don't specify a gap value, FlowLayout uses 5 for the default gap value.

30 Grid Layout A GridLayout places components in a grid of cells. Each component takes all the available space within its cell, and each cell is exactly the same size. If you resize the GridLayout window, it changes the cell size so that the cells are as large as possible, given the space available to the container.

31 Grid Layout Example Container contentPane = getContentPane(); contentPane.setLayout(new GridLayout(0,2)); contentPane.add(new JButton("Button 1")); contentPane.add(new JButton("2")); contentPane.add(new JButton("Button 3")); contentPane.add(new JButton("Long-Named Button 4")); contentPane.add(new JButton("Button 5")); The constructor tells the GridLayout class to create an instance that has two columns and as many rows as necessary.

32 Grid Output

33 The GridLayout API The GridLayout class has two constructors: public GridLayout(int rows, int columns) public GridLayout(int rows, int columns, int horizontalGap, int verticalGap) At least one of the rows and columns arguments must be nonzero. The horizontalGap and verticalGap arguments to the second constructor allow you to specify the number of pixels between cells. If you don't specify gaps, their values default to zero.

34 Why Layouts? Can use Absolute Layout Layouts provide flexibility in different environments with different screen resolutions. Font sizes, component contents may change (internationalization)

35 Events & Event Handling Example… User clicks on a button Button is source of event object Event object passed to associated listener object Listener object executes associated method to perform desired task (save file, quit program, …) Event listener object (executes method) Event Object Event cause (mouse, keyboard, timer, …) Event Source object

36 Setting up Event Handling Create listener class Using new or existing class, simply Implement desired event listener interface Putting code for desired action in its methods In application (e.g. Frame) Create instance of listener class Add as listener of source object can have any number of listeners for each event Source & listener can be same object!

37 Understanding Events When button is pressed actionPerformed method of every item in button’s actionListeners list called Similarly for textfield When Frame close button is pressed windowClosing method of every item in Frame’s windowListeners list called {Frame} {label} {textfield} {button} components ActionListeners actionPerformed {MyListener} actionPerformed WindowListeners windowClosing

38 Event Classes AWTEvent EventObject AdjustmentEvent ComponentEvent TextEvent ItemEvent ActionEvent InputEvent WindowEvent MouseEvent KeyEvent ContainerEvent FocusEvent PaintEvent ListSelectionEvent

39 Event Examples User clicks a button, presses Return while typing in a text field, or chooses a menu item  ActionListener 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

40 How to Implement an Event Handler In the declaration for the event handler class, specify that the class either implements a listener interface or extends a class that implements a listener interface. For example: public class MyClass implements ActionListener { Register an instance of the event handler class as a listener upon one or more components. For example: someComponent.addActionListener(instanceOfMyClass) Implement the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) {...//code that reacts to the action... }

41 public class MC extends JFrame implements ActionListener { private int noClicks = 0; private JButton button = new JButton("click me !"); private JTextArea textArea = new JTextArea(5, 40); private JLabel label = new JLabel("Here you can see the number of button clicks") ; private JProgressBar progressBar = new JProgressBar(JProgressBar.HORIZONTAL); public MC(String title) { super(title); Container cp = getContentPane(); cp.setLayout(new BoxLayout(cp, BoxLayout.Y_AXIS)); cp.add(button); JScrollPane scrollPane = new JScrollPane(textArea); cp.add(scrollPane);cp.add(label); cp.add(progressBar); button.addActionListener(this); }

42 Action Example Cont. public void actionPerformed(ActionEvent e) { noClicks++; textArea.append("Button clicked " + noClicks + " times so far \n"); label.setText("You clicked " + noClicks + " times"); progressBar.setValue(noClicks); } public static void main(String[] args) { MyClass frame = new MyClass("Simple Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.show(); }

43 Listener Class Flavors public class MyClass implements MouseListener {... someObject.addMouseListener(this);... public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) {...//Event handler implementation goes here... }

44 Adapter Classes Java comes with a variety of adapter classes that implement Listener interfaces but have empty implementations. One can extend an adapter class and only override events that are of interest

45 Adapter Example An example of extending an adapter class instead of directly implementing a listener interface. public class MyClass extends MouseAdapter {... x.addMouseListener(this);... public void mouseClicked(MouseEvent e) { //Event handler implementation //goes here... }

46 Using an Inner class … What if your class has to extend another one? public class MyClass extends Applet {... x.addMouseListener(new MyAdapter());... class MyAdapter extends MouseAdapter { public void mouseClicked(MouseEvent e) {...//Event handler implementation //goes here... }

47 Using an Anonymous Inner class public class MyClass extends Applet {... x.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) {...//Event handler impl. } });... } } an inner class can refer to instance variables and methods just as if its code is in the containing class

48 Example class PanelJ2 extends JPanel { public PanelJ2() { JButton b = new JButton( "OK"); setLayout( new BorderLayout() ); setBackground( Color.red); add( b, BorderLayout.SOUTH); b.addActionListener( new ExampleActionListener()); } // restores screen after window has been covered, minimized, public void paintComponent( Graphics g) { super.paintComponent( g); g.drawRect( 50, 50, 200, 100); g.drawString( "Hello", 125, 100 ); }

49 Action Listener class ExampleActionListener implements ActionListener { public void actionPerformed( ActionEvent e) { System.out.println( "Button Pressed"); }

50 Putting 3 of PanelJ2 … class MyJFrame extends JFrame { public MyJFrame() { Container c = getContentPane(); c.setLayout( new FlowLayout() ); c.add( new PanelJ2()); setTitle( "ExampleJ3 - Hi there"); setBounds( 100, 150, 300, 300); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); setVisible(true); }

51 Outcome …

52 Put them inside an applet public class AppletExample extends Applet { public void init() { setLayout( new FlowLayout() ); add( new PanelJ2()); }

53 Applet outcome

54 Which button ? Let’s say you have three buttons on your application. How can you tell which button was pressed? We need something distinct about the event object to decide what to do We can use getSource() method

55 ButtonPanel class ButtonPanel extends JPanel implemnts ActionListener{ public ButtonPanel() { yellowButton = new JButton("Yellow"); blueButton = new JButton("Blue"); redButton = new JButton("Red"); add(yellowButton); add(blueButton); add(redButton); yellowButton.addActionListener(this); blueButton.addActionListener(this); redButton.addActionListener(this); } private JButton yellowButton, blueButton, redButton; }

56 actionPerformed method public void actionPerformed(ActionEvent evt){ Object source = evt.getSource(); Color color = getBackground(); if (source == yellowButton) color = Color.yellow; else if (source == blueButton) color = Color.blue; else if (source == redButton) color = Color.red; setBackground(color); repaint(); }

57 An alternative? We used the same listener object for all the buttons (ButtonPanel itself) Another approach would be to use different listeners who knows about what they should do when the event happens

58 ColorAction inner class private class ColorAction implements ActionListener { public ColorAction(Color c) { backgroundColor = c; } public void actionPerformed(ActionEvent event) { setBackground(backgroundColor); } private Color backgroundColor; }

59 New constructor … public ButtonPanel() { // create buttons JButton yellowButton = new JButton("Yellow");... // add buttons to panel add(yellowButton); add(blueButton); add(redButton); // create button actions ColorAction yellowAction = new ColorAction(Color.YELLOW); ColorAction blueAction = new ColorAction(Color.BLUE); ColorAction redAction = new ColorAction(Color.RED); // associate actions with buttons yellowButton.addActionListener(yellowAction); blueButton.addActionListener(blueAction); redButton.addActionListener(redAction); }

60 ColorAction, another aproach class ColorAction implements ActionListener { public ColorAction(Color c, JPanel p) { backgroundColor = c; buttonPanel = p; } public void actionPerformed(ActionEvent event) { buttonPanel.setBackground(backgroundColor); } private Color backgroundColor; private JPanel buttonPanel; }

61 The program..

62 Mouse Listener Example public class MouseMove extends JFrame { private Rectangle box; private int x,y; public static void main(String[] args) { MouseMove m = new MouseMove(); } public MouseMove() { super("Mouse Demonstration"); Container cp=getContentPane(); JPanel mousePanel = new MousePanel(); mousePanel.setPreferredSize(new Dimension(300, 300)); cp.add(mousePanel); pack(); setVisible(true); }

63 class MousePanel extends JPanel { int x,y; public MousePanel() { addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent event) { x=event.getX(); y=event.getY(); System.out.println(event); repaint(); } } ); } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString("You clicked here", x, y); }


Download ppt "CS102 – GUI Based on : David Davenport’s slides Spring 2002 References:"

Similar presentations


Ads by Google