1 / 73

Chapter 6 AWT Programming

Chapter 6 AWT Programming. Describe how to build GUI : frame, panel, text field etc. Learn how to write handling method for variety of event types Use AWT for user interface programming Introduction to JFC Lab. AWT.

Download Presentation

Chapter 6 AWT 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. Chapter 6 AWT Programming • Describe how to build GUI : frame, panel, text field etc. • Learn how to write handling method for variety of event types • Use AWT for user interface programming • Introduction to JFC • Lab

  2. AWT • Provides basic GUI components which are used in all Java applets and applications • Has super classes which can be extended and their properties inherited; classes can be also abstract • Ensures that every GUI component that is displayed on the screen is a subclass of the abstract class Component • Contains Container which is an abstract subclass of Component and which includes two subclasses • Panel • Window

  3. java.awt Package

  4. Containers • The two main types of containers are Window and Panel • Windows are objects of java.awt.Window • Panels are objects of java.awt.Panel

  5. Building Graphical User Interfaces • The position and size of a component in a container is determined by a layout manager. • You can control the size or position of components by disabling the layout manager setLayout(null) You must then use setLocation(), setSize(), or setBounds() on components to locate them in the container. This approach results in platform-dependent layouts due to the differences between windows systems and font sizes.

  6. Frames • Are subclasses of Window • Have title and resize corners • Inherit from Component and add components with the add method • Can be used to create invisible Frame objects with a title specified by String • Have Border Layout as the default layout manager • Use the set Layout method to change the default layout manager

  7. Frames import java.awt.*; public class MyFrame extends Frame { public static void main (String args[]){ MyFrame fr = new MyFrame(“Hello Out There!”); fr.setSize(500,500); fr.setBackground(Color.white); fr.setVisible(true); } public MyFrame(String str){ super(str) }

  8. Panels • Provide a space for components • Allow subpanels to have their own layout manager • Add components with the add method

  9. Panels import java.awt.*; public class FrameWithOanel extends Frame{ public FrameWithPanel (String str) { super(str); } public static void main (String args[]){ FrameWithPanel fr = new FrameWithPanel(“Frame with Panel”); Panel pan = new Panel(); fr.setSize(200,200); fr.setBackgroud(Color.blue); fr.setLayout(null); pan.setSize(100,100); pan.setBackground(Color.yellow); fr.add(pan); fr.setVisible(true); }

  10. Container Layout • Flow Layout • Border Layout • Grid Layout • Card Layout • GridBag Layout

  11. Flow Layout import java.awt.*; public class MyFlow { private Frame f; private Button button1, button2, button3; public static void main (String args[]){ MyFlow mflow = new MyFlow(); mflow.go(); } public void go(){ f = new Frame(“Flow Layout”); f.setLayout(new FlowLayout()); button1 = new Button(“ok”); button2 = new Button(“Open”); button3 = new Button(“Close”); f.add(button1); f.add(button2); f.add(button3); f.setSize(100,100); f.setVisible(true); }

  12. Border Layout f.add(bs, “South”); f.add(be,”East”); f.add(bw, “West”); f.add(bc, “Center”); f.setSize(200,200); f.setVisible(true); } } import java.awt.*; public class ExGui2{ private Frame f; private Button bn, bs, bw, be, bc; public static void main(String args[]){ ExGui2 guiWindow2 = new ExGui2(); guiWindow2.go(); } public void go(){ f = new Frame(“Border Layout”); f.setLayout(new BorderLayout()); bn = new Button(“B1”); bs = new Button(“B2”); be = new Button(“B3”); bw = new Button(“B4”); bc = new Button(“B5”); f.add(bn, “North”);

  13. Grid Layout Manager b2 = new Button(“2”); b3 = new Button(“3”); b4 = new Button(“4”); b5 = new Button(“5”); b6 = new Button(“6”); f.add(b1); f.add(b2); f.add(b3); f.add(b4); f.add(b5); f.add(b6); f.pack(); // to arrange the components f.setVisible(true); } } import java.awt.*; public class GridEx { private Frame f; private Button b1, b2, b3, b4, b5, b6; public static void main(String args[]){ GridEx grid = new GridEx(); grid.go(); } public void go(){ f = new Frame(“Grid example”); f.setLayout(new GridLayout(3,2); b1 = new Button(“1”);

  14. Card Layout Manager import java.awt.*; import java.awt.event.*; public class CardTest implements MouseListener { Panel p1, p2, p3, p4, p5; Label l1, l2, l3, l4, l5; // Declare a CardLayout object // to call its methods. CardLayout myCard; Frame f; public static void main (String args[]) { CardTest ct = new CardTest(); ct.init(); }

  15. Card Layout Manager public void init() { f = new Frame ("Card Test"); myCard = new CardLayout(); f.setLayout(myCard); // Create the panels that I want // to use as cards. p1 = new Panel(); p2 = new Panel(); l1 = new Label("This is the first Panel"); p1.setBackground(Color.yellow); p1.add(l1); l2 = new Label("This is the second Panel"); p2.setBackground(Color.green); p2.add(l2); // Set up the event handling here. p1.addMouseListener(this); p2.addMouseListener(this); // Add each panel to my CardLayout f.add(p1, "First"); f.add(p2, "Second"); // Display the first panel. myCard.show(f, "First"); f.setSize(200,200); f.setVisible(true); } public void mousePressed(MouseEvent e) { myCard.next(f); } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } }

  16. GridBag Layout Manager • Complex layout facilities can be placed in a grid • A Single component can take its preferred size. • A component can extend over more than one cell

  17. Creating Panels and Complex layouts • Creat Panel (container) and mix with other components in the same Frame.

  18. Creating Panels and Complex layouts public void go() { f = new Frame("GUI example 3"); bw = new Button("West"); bc = new Button("Work space region"); f.add(bw, BorderLayout.WEST); f.add(bc, BorderLayout.CENTER); p = new Panel(); bfile = new Button("File"); bhelp = new Button("Help"); p.add(bfile); p.add(bhelp); f.add(p, BorderLayout.NORTH); f.pack(); f.setVisible(true); } } import java.awt.*; public class ExGui3 { private Frame f; private Panel p; private Button bw, bc; private Button bfile, bhelp; public static void main(String args[]) { ExGui3 gui = new ExGui3(); gui.go(); }

  19. Lab 6 Lab 6-1 :

  20. EVENT :What is an Event? • Event : Objects that describe what happened • Event sources : The generator of an event • Event handles - A method that receives an event object, deciphers it, and processes the user’s interaction.

  21. Event Model Event Object Event Source Event Listener

  22. Event Model

  23. Event Model import java.awt.*; public class TestButton{ public static void main(String args[]){ Frame f = new Frame(“Test”); Button b = new Button(“Press Me!”); b.addActionListener(new ButtonHandler()); f.add(b,”Center”); f.pack(); f.setVisible(true); } } import java.awt.event.*; public void actionPerformed(ActionEvent e){ System.out.println(“Acton occurred”); System.out.println(“Button’s label is : “+ e.getActionCommand()); } }

  24. Event Categories

  25. Event Handling Summary Interface Methods Parameter Event generated by __________________________________________________________________________________________ ActionListener actionPerformed ActionEvent Button getActionCommand List getModifiers MenuItem TextField _________________________________________________________________________________________ AdjustmentListener adjustmentValueChanged AdjustmentEvent Scrollbar getAdjustable getAdjustmentType getValue _________________________________________________________________________________________

  26. Event Handling Summary Interface Methods Parameter Event generated by __________________________________________________________________________________________ ItemListener itemStatechanged ItemEvent Checkbox getItem CheckboxMenuItem getItemSelectable Choice getStateChange List _________________________________________________________________________________________ TextListener textValueChanged TextEvent TextComponent _________________________________________________________________________________________ ComponentListener componentMoved ComponentEvent Component componentHidden getComponent componentResized

  27. Event Handling Summary Interface Methods Parameter Event generated by __________________________________________________________________________________________ ContainerListener componentAdded ContainerEvent Container componentRemoved getChild getContainer _________________________________________________________________________________________ FocusListener focusGained FocusEvent Component focusLost IsTemporary _________________________________________________________________________________________ KeyListener keyPressed KeyEvent Component keyReleased getKeyChar keyTyped getKeyCode getKeyModifiersText getKeyText IsActionKey

  28. Event Handling Summary Interface Methods Parameter Event generated by __________________________________________________________________________________________ MouseListener mousePressed MouseEvent Component mouseReleased getClickCount mouseEntered getX mouseExited getY mouseClicked getPoint TranslatePoint IsPopupTrigger _________________________________________________________________________________________ MouseMotionListener mouseDragged MouseEvent Component mouseMoved _________________________________________________________________________________________

  29. Event Handling Summary Interface Methods Parameter Event generated by __________________________________________________________________________________________ WindowListener windowClosing WindowEvent Window windowOpened getWindow windowIconified windowDeiconified windowClosed windowActivated windowDeActivated

  30. Event Example public void go() { f = new Frame("Two listeners example"); f.add (new Label ("Click and drag the mouse"), BorderLayout.NORTH); tf = new TextField (30); f.add (tf, BorderLayout.SOUTH); f.addMouseMotionListener(this); f.addMouseListener (this); f.setSize(300, 200); f.setVisible(true); } import java.awt.*; import java.awt.event.*; public class TwoListen implements MouseMotionListener, MouseListener { private Frame f; private TextField tf; public static void main(String args[]) { TwoListen two = new TwoListen(); two.go(); }

  31. Event Example public void mouseExited (MouseEvent e) { String s = "The mouse has left the building"; tf.setText (s); } // Unused MouseMotionListener method. public void mouseMoved (MouseEvent e) { } // Unused MouseListener methods. public void mousePressed (MouseEvent e) { } public void mouseClicked (MouseEvent e) { } public void mouseReleased (MouseEvent e) { } } // These are MouseMotionListener events public void mouseDragged (MouseEvent e) { String s = "Mouse dragging: X = " + e.getX() + " Y = " + e.getY(); tf.setText (s); } public void mouseEntered (MouseEvent e) { String s = "The mouse entered"; tf.setText (s); }

  32. Multiple Listeners • Multiple listeners cause unrelated parts of a program to act the same. • All registered listeners have their handler called when the event occurs.

  33. Event Adapters • The Listener routine that you define can extend the Adapter class and override only the methods that you need. import java.awt.*; import java.awt.event.*; public class MouseClickHandler extenders MouseAdapter{ public void mouseClicked (MouseEvent e){ // Do Something } }

  34. Lab 6 Lab 6-2 :

  35. AWT Component • AWT components provide mechanisms for controlling the interface appearance, including color and font • The AWT also supports printing.

  36. Button public void go() { f = new Frame("Sample Button"); b = new Button("Sample"); b.addActionListener(this); f.add(b); f.pack(); f.setVisible(true); } public void actionPerformed( ActionEvent ae) { System.out.println("Button press received."); System.out.println("Button's action command is: "+ ae.getActionCommand()); } } import java.awt.*; import java.awt.event.*; public class SampleButton implements ActionListener { Frame f; Button b; public static void main (String args[]) { SampleButton sampleButton = new SampleButton(); sampleButton.go(); }

  37. Checkbox import java.awt.*; import java.awt.event.*; public class SampleCheckbox implements ItemListener { Frame f; Checkbox one, two, three; public static void main (String args[]) { SampleCheckbox sampleCheckbox = new SampleCheckbox(); sampleCheckbox.go(); }

  38. Checkbox public void go() { f = new Frame("Sample Checkbox"); one = new Checkbox("One", true); two = new Checkbox("Two", false); three = new Checkbox("Three", false); one.addItemListener(this); two.addItemListener(this); three.addItemListener(this); f.setLayout(new FlowLayout()); f.add(one); f.add(two); f.add(three); f.pack(); f.setVisible(true); } public void itemStateChanged(ItemEvent ev) { String state = "deselected"; if (ev.getStateChange() == ItemEvent.SELECTED) { state = "selected"; } System.out.println (ev.getItem() + " " + state); } }

  39. Checkbox Group-Radio Buttons import java.awt.*; import java.awt.event.*; public class SampleRadio implements ItemListener { Frame f; CheckboxGroup cbg; Checkbox one; Checkbox two; Checkbox three; public static void main (String args[]) { SampleRadio sampleRadio = new SampleRadio(); sampleRadio.go(); }

  40. Checkbox Group-Radio Buttons f.pack(); f.setVisible(true); } public void itemStateChanged(ItemEvent ev) { String state = "deselected"; if (ev.getStateChange() == ItemEvent.SELECTED) { state = "selected"; } System.out.println (ev.getItem() + " " + state); } } public void go() { f = new Frame("Sample Radiobuttons"); cbg = new CheckboxGroup(); one = new Checkbox("One", cbg, false); two = new Checkbox("Two", cbg, false); three = new Checkbox("Three", cbg, true); f.setLayout(new FlowLayout()); one.addItemListener(this); two.addItemListener(this); three.addItemListener(this); f.add(one); f.add(two); f.add(three);

  41. Choice public void go() { f = new Frame("Sample Choice"); choice = new Choice(); choice.addItem("First"); choice.addItem("Second"); choice.addItem("Third"); choice.addItemListener(this); f.add(choice, BorderLayout.CENTER); f.pack(); f.setVisible(true); } public void itemStateChanged(ItemEvent ev) { String state = "deselected"; if (ev.getStateChange() == ItemEvent.SELECTED) { state = "selected"; } System.out.println (ev.getItem() + " " + state); } } import java.awt.*; import java.awt.event.*; public class SampleChoice implements ItemListener { Frame f; Choice choice; public static void main (String args[]) { SampleChoice sampleChoice = new SampleChoice(); sampleChoice.go(); }

  42. Canvas public void keyTyped(KeyEvent ev) { s += ev.getKeyChar(); // While this will work, it is // not a good drawing technique as // it does not draw from a model. // See applet module for more details. getGraphics().drawString(s, 0, 20); } public void keyPressed(KeyEvent ev) { } public void keyReleased(KeyEvent ev) { } } import java.awt.*; import java.awt.event.*; public class MyCanvas extends Canvas implements KeyListener { String s = ""; public static void main(String args[]) { Frame f = new Frame("Canvas"); MyCanvas mc = new MyCanvas(); f.add(mc, BorderLayout.CENTER); f.setSize(150, 150); mc.addMouseListener(mc); mc.addKeyListener(mc); f.setVisible(true); }

  43. Label A Label object displays a single line of static Text. Label l = new Label(“Hello”); add(l);

  44. TextField The TextField is a single line text input device. For Example TextField f = new TextField(“Single line”, 30); f.addActionListener(this); add(f);

  45. TextArea import java.awt.*; import java.awt.event.*; public class SampleTextArea { Frame f; TextArea ta; public static void main (String args[]) { SampleTextArea sampleTextArea = new SampleTextArea(); sampleTextArea.go(); } public void go() { f = new Frame("Sample TextArea"); ta = new TextArea("Initial text", 4, 20); f.add(ta, BorderLayout.CENTER); f.pack(); f.setVisible(true); } }

  46. TextComponent • TextArea and TextField are subclasses • TextComponent implements TextListener

  47. List A List presents text options which are dusplayed in a region that allows several items to be viewed at one times. The List is scrollable and supports both single and multiple-selection modes. List l = new List(4, true); l.add(“Hello”); l.add(“there”); l.add(“how”); l.add(“are”);

  48. Dialog • A Dialog component is associated with a Frame. import java.awt.event.*; public class SampleDialog implements ActionListener { Frame f; Dialog d; Panel dp; Button db1; Button db2; Label dl; Button b; public static void main (String args[]) { SampleDialog sampleDialog = new SampleDialog(); sampleDialog.go(); }

  49. Dialog b = new Button("Self Destruct"); // Register listener for buttons. b.addActionListener(this); db1.addActionListener(this); db2.addActionListener(this); f.add(b, BorderLayout.CENTER); f.setSize(400,400); f.setVisible(true); } • public void go() { • f = new Frame("SampleDialog"); • // Set up dialog. • d = new Dialog(f, "Dialog box", true); • dp = new Panel(); • dp.setLayout(new FlowLayout()); • db1 = new Button("OK"); • db2 = new Button("Not on your life!!!"); • dp.add(db1); • dp.add(db2); • dl = new Label ("Are you absolutely sure you want to do this?"); • d.add(dl,BorderLayout.NORTH); • d.add(dp,BorderLayout.SOUTH); • d.pack();

  50. Dialog // Handler for all buttons. public void actionPerformed( ActionEvent ae) { String buttonPressed = ae.getActionCommand(); if (buttonPressed.equals("Self Destruct")) { d.setVisible(true); } else if (buttonPressed.equals("OK")) { System.out.println ("Process terminated!!!"); System.exit(0); } else { d.setVisible(false); } } }

More Related