1 / 60

GUI Components

GUI Components. Structure. Container Class Structure. setBackground(c) setForeground(c) setFont(f) setVisible(b) paint(g) repaint() setSize(x,y). getSize().width getWidth() getSize().height getHeight(). Component Class Methods. add(x) remove(x) removeAll() setLayout(l)

Download Presentation

GUI Components

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 Components

  2. Structure

  3. Container Class Structure

  4. setBackground(c) setForeground(c) setFont(f) setVisible(b) paint(g) repaint() setSize(x,y) getSize().width getWidth() getSize().height getHeight() Component Class Methods

  5. add(x) remove(x) removeAll() setLayout(l) getLayout() pack() -- window only paint(g) setVisible(b) getComponents() Container Class Methods

  6. Layout Managers • FlowLayout: Places components from left to right, top to bottom allowing you no control over position. • Constructors: • FlowLayout(): the components are centered • FlowLayout(a): a is FlowLayout.LEFT or FlowLayout.RIGHT • FlowLayout(a, dx, dy) dx & dy are distances between components.

  7. BorderLayout • Designates five positions in the screen: North, South, East, West, and Center. • BorderLayout(dx, dy) dx & dy are distances between components • add(“place”, c) : arranges the component c • “place” can be North, South, East, West, or Center

  8. Border Layout Example /* File: BorderLayoutDemo.java */ import java.awt.*;import java.applet.Applet;public class BorderLayoutDemo extends Applet { public void init() { setLayout(new BorderLayout()); add(new Button("North") ,BorderLayout.NORTH); add(new Banner("The Center") ,BorderLayout.CENTER); add(new Button("East") ,BorderLayout.EAST); add(new Button("West") ,BorderLayout.WEST); add(new Button("South") ,BorderLayout.SOUTH); } } // BorderLayoutDemo class

  9. GridLayout • Lets you specify a two-dimensional grid of rows and columns. • All components are the same size, and the size will automatically change as the window is manipulated. • GridLayout(r,c) : sets number of rows and columns (Use zero when you need an arbitrary number) • GridLayout(r,c,dx,dy) dx & dy are spacing distances

  10. GridLayout Example /* File: GridLayoutDemo.java */import java.awt.*;import java.applet.Applet;public class GridLayoutDemo extends Applet{ public void init() { int rows = 3; int columns = 3; Panel gridP = new Panel(); gridP.setLayout(new GridLayout(rows,columns,5,10)); for(int r = 1; r <= rows; r++) for (int c = 1; c <= columns; c++) if (r == 2 && c == 2) gridP.add(new Banner("TheCenter")); else gridP.add(new Button(r + " , " + c)); add(gridP); } }// class GridLayoutDemo

  11. CardLayout • Lets you create a “stack of cards” where only one of the cards is visible at any given time.

  12. CardLayout Demo /* File: CardDemo.java*/ import java.awt.*; import java.applet.Applet; import java.awt.event.*; public class CardDemo extends Applet implements ActionListener { Button first,prev,next,last; Panel displays; CardLayout cLayout; public void init() { // The applet has a border layout setLayout(new BorderLayout()); // Create the buttons for controlling the card panel. // The button panel defaults to a FlowManager Panel buttonP = new Panel(); first = new Button("First"); buttonP.add(first); prev = new Button("Previous"); buttonP.add(prev); next = new Button("Next"); buttonP.add(next); last = new Button("Last"); buttonP.add(last); add(buttonP,BorderLayout.SOUTH); first.addActionListener(this); prev.addActionListener(this); next.addActionListener(this); last.addActionListener(this);

  13. CardLayout Demo // Create the card panel, and card layout displays = new Panel(); for(int i = 1; i <= 5; i++) displays.add( new Banner("Picture " + i)); cLayout = new CardLayout(); displays.setLayout(cLayout); add(displays, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { Button b = (Button)e.getSource(); if (b == next) cLayout.next(displays); else if (b == prev) cLayout.previous(displays); else if (b == last) cLayout.last(displays); else if (b == first) cLayout.first(displays); } } // class CardDemo

  14. CardLayout Demo

  15. GridBagLayout • The most complicated an powerful LayoutManager. • Separates the window into a number of boxes. • You may set the size of rows and columns of boxes • Components may span multiple boxes (display area) • You specify the box(es) that hold a component • Number of total boxes is based on component placement • Declaration: GridBagLayout m = new GridBagLayout(); setLayout(m);

  16. Each component in a GridBagLayout must use an instance of the GridBagConstraints class to set its properties. For example: GridBagConstraints con = new GridBagConstraints(); con.X; con.Y; ... (uses methods X & Yof con to set some properties) m.setConstraints(comp, con); connects the constrains in GridBagConstraints con to the component comp in GridBagLayout m. The component can then be added to m with add(comp); GridBagConstraints()

  17. GridBagConstraints methods: • gridx, gridy: set column and row where component will begin. Starts with 0. Default value is Relative (to the right for gridx, down for gridy • gridwidth, gridheight: sets the number of boxes the component will occupy. Default is 1. Value REMAINDER means the rest of the row or col. • fill, anchor: deal with how the component will fill its area and/or what position in the box it will take (anchor). Default values: NONE, CENTER • insets, ipadx, ipady: allow you to set space around components. • weightx, weighty: set up how any extra space is allotted to components in each column (x) or row (y). Components with higher weight get more space. Default values: 0.

  18. GridBagLayout Example: // File: GridBagLayoutDemo.java import java.awt.*;import java.applet.*; public class GridBagLayoutDemo extends Applet { public void init() { GridBagLayout manager = new GridBagLayout(); setLayout(manager); GridBagConstraints constraints; // arrange the checkboxes Checkbox chkBig = new Checkbox("Big"); Checkbox chkActive = new Checkbox("Active"); constraints = new GridBagConstraints(); constraints.weighty = 1; constraints.anchor = GridBagConstraints.SOUTHWEST; constraints.gridy = 0; constraints.gridx = 0; // row 0, col 0 manager.setConstraints(chkBig, constraints); add(chkBig); constraints.anchor = GridBagConstraints.NORTHWEST; constraints.gridy = 1; constraints.gridx = 0; // row 1, col 0 manager.setConstraints(chkActive, constraints); add(chkActive);

  19. GridBagLayout Example: // arrange the canvas Canvas cvs = new Canvas(); cvs.setBackground(Color.darkGray); constraints = new GridBagConstraints(); constraints.gridy = 0; constraints.gridx = 1; // row 0, col 1 constraints.gridwidth = 2; constraints.gridheight = 2; constraints.fill = GridBagConstraints.BOTH; manager.setConstraints(cvs, constraints); add(cvs); // arrange the label Label lblFile = new Label("File: ", Label.RIGHT); constraints = new GridBagConstraints(); constraints.gridy = 2; constraints.gridx = 0; // row 2, col 0 constraints.insets = new Insets(10, 0, 10, 0); // 10 pixels above and below manager.setConstraints(lblFile, constraints); add(lblFile); // arrange the TextField TextField txtFile = new TextField(); constraints.gridwidth = 2; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.gridy = 2; constraints.gridx = 1; // row 2, col 1 manager.setConstraints(txtFile, constraints); add(txtFile);

  20. GridBagLayout Example: // arrange the buttons Button btnOK = new Button("OK"); Button btnCancel = new Button("Cancel"); Button btnTest = new Button("Test"); constraints = new GridBagConstraints(); constraints.gridy = 3; constraints.gridx = 0; // row 3, col 0 constraints.ipadx = 5; constraints.anchor = GridBagConstraints.EAST; manager.setConstraints(btnOK, constraints); add(btnOK); constraints.weightx = 1; constraints.gridy = 3; constraints.gridx = 1; // row 3, col 1 constraints.anchor = GridBagConstraints.CENTER; manager.setConstraints(btnCancel, constraints); add(btnCancel); constraints.gridy = 3; constraints.gridx = 2; // row 3, col 2 constraints.anchor = GridBagConstraints.WEST; manager.setConstraints(btnTest, constraints); add(btnTest); }}

  21. GridBagLayout Example: <html> <head> <title>GridBagLayout demonstration</title> </head> <body> <applet code=GridBagLayoutDemo.class width=300 height=200> </applet> </body></html>

  22. Output Components • Label -- basic text output using fonts. • Canvas -- area for drawing or writing text.

  23. The Label Component • Methods: • Constructors: Label(“text”); Label(“text”,adj); • text is the label’s text, adj is the label’s alignment • setText(“text”); getText(); setAlignment(adj); getAlignment(); • Values for adj: Label.LEFT (the default), Label.CENTER, Label.RIGHT

  24. Label Example: import java.awt.*;class ShowLabel extends Frame { public static void main(String[] arg) {ShowLabel w = new ShowLabel (); Label l = new Label("Welcome to Java", Label.CENTER); l.setFont( new Font("SansSerif", Font.BOLD, 24) ); l.setBackground(Color.yellow); l.setForeground(Color.blue); // set the window's properties w.setLayout( new GridLayout(1,1) ); w.add(l); w.setSize(400, 150); w.setVisible(true); } }

  25. Canvas • Used only for showing drawings & text • Not a container, like Panel. import java.awt.*; public class CircleCanvas extends Canvas { public boolean filled = true; public boolean inTheCenter = true; public boolean blackBackground = false; public void paint(Graphics g) {int diam =Math.min(getSize().width, getSize().height); int x0 = 0; if (inTheCenter) x0 = (getSize().width - diam) / 2; if (blackBackground) setBackground(Color.black); else setBackground(Color.white); if (filled) g.fillOval(x0, 0, diam, diam); else g.drawOval(x0, 0, diam, diam); }}

  26. Canvas Continued import java.awt.*;import java.applet.*; public class CircleDemo extends Applet { CircleCanvas circle = new CircleCanvas(); Label label = new Label("A circle", Label.CENTER); public void init() { circle.setForeground(Color.blue); label.setFont( new Font("Serif", Font.BOLD, 18) ); setLayout( new GridLayout(2, 1) ); add(circle); add(label); setVisible(true); }} <html> <head> <title>A canvas demonstration applet</title> </head> <body> A canvas demonstration applet <br> <applet code=CircleDemo.class width=400 height=150> </applet> </body></html>

  27. Clickable Input Components • Button • CheckBox • List • Choice • Scrollbar

  28. Button • Methods: • Constructors: Button(); Button(“text”) • setLabel(“text”); getLabel() • b.setActionCommand(“text”); Connects the text text to button b. • b.addActionListener(l); Connects a listener l of class ActionListener to button b. • Define method actionPerformed in the listener: • Methods then called in the listener: • e.getSource(): returns the object where event occurred • b.getLabel(): returns text in button • public void actionPerformed(ActionEvent e) { • //we get here when the user presses the button • }

  29. Button Example: import java.awt.*; import java.awt.event.*; import java.applet.*; public class CircleButtonDemo extends Applet implements ActionListener { private CircleCanvas circle = new CircleCanvas(); private Panel panel = new Panel(); private Button btnBlue = new Button("Blue"); private Button btnRed = new Button("Red"); private Button btnYellow = new Button("Yellow"); public void init() { circle.setForeground(Color.green); setLayout( new GridLayout(2, 1) ); add(circle); add(panel); panel.setLayout (new GridLayout(1, 3) ); panel.add(btnBlue); panel.add(btnRed); panel.add(btnYellow);

  30. Button Example: // connect the listeners btnBlue.addActionListener(this); btnRed.addActionListener(this); btnYellow.addActionListener(this); setVisible(true); } // define listeners public void actionPerformed(ActionEvent e) { // check to see which button has been clicked on if (e.getSource() == btnBlue) circle.setForeground(Color.blue); else if (e.getSource() == btnRed) circle.setForeground(Color.red); else if (e.getSource() == btnYellow) circle.setForeground(Color.yellow); circle.repaint(); } }

  31. Button Example: <html> <head> <title>A button demonstration applet</title> </head> <body> A button demonstration applet <br> <applet code=CircleButtonDemo.class width=400 height=150> </applet> </body> </html>

  32. Checkboxes • May be grouped to form radio buttons • Declarations: • Checkbox x1 = new Checkbox(); not selected, no text • Checkbox x2 = new Checkbox(“text”); not selected, with text • Checkbox x3 = new Checkbox(“text”, false); not selected • Checkbox x4 = new Checkbox(“text”, true); selected • CheckboxGroup gr = new CheckboxGroup(); a set of radio buttons • Checkbox r1 = new Checkbox(“text1”,bool, gr); • Checkbox r2 = new Checkbox(“text2”,bool, gr);only one r# is true • Checkbox r3 = new Checkbox(“text3”,bool, gr);

  33. setLabel(“text); getLabel(); setState(bool); x.setCheckboxGroup(g); puts x into group g. x.getCheckboxGroup(); gives the group x is in. g.setSelectedCheckbox(x); x in group g will be selected g.getSelectedCheckbox(); return selected Checkbox in g. Checkbox Methods

  34. Checkbox Listeners • To connect a listener to a Checkbox: • x.addItemListener(l); • Define the method itemStateChanged in the listener: • public void itemStateChanged (ItemEvent e) { • // we get here when user clicks on a checkbox • } • Method called in the listener: • e.getSource(); returns the object where the event occurred.

  35. Checkbox Example import java.awt.*; import java.awt.event.*; import java.applet.*; public class CircleCheckboxDemo extends Applet implements ItemListener { private CircleCanvas circle = new CircleCanvas(); private Panel panelMiddle = new Panel(); private CheckboxGroup grpOption = new CheckboxGroup(); private Checkbox chkBlue = new Checkbox("Blue", true, grpOption); private Checkbox chkRed = new Checkbox("Red", false, grpOption); private Checkbox chkYellow = new Checkbox("Yellow", false, grpOption); private Panel panelBottom = new Panel(); private Checkbox chkFilled = new Checkbox("Filled", true); private Checkbox chkCentered = new Checkbox("Centered", true); private Checkbox chkBlack = new Checkbox("Black Background", false);

  36. public void init() { circle.setForeground(Color.green); setLayout (new GridLayout(3, 1) ); add(circle); add(panelMiddle); // arrange the radio buttons panelMiddle.setLayout( new GridLayout(1, 3) ); panelMiddle.add(chkBlue); panelMiddle.add(chkRed); panelMiddle.add(chkYellow); // connect the listener chkBlue.addItemListener(this); chkRed.addItemListener(this); chkYellow.addItemListener(this); add(panelBottom); // arrange the checkboxes panelBottom.setLayout( new GridLayout(3, 1) ); panelBottom.add(chkFilled); panelBottom.add(chkCentered); panelBottom.add(chkBlack);

  37. Checkbox Example: // connect the listener chkFilled.addItemListener(this); chkCentered.addItemListener(this); chkBlack.addItemListener(this); setVisible(true); } // listener public void itemStateChanged(ItemEvent e) { if (e.getSource() == chkBlue) circle.setForeground(Color.blue); else if (e.getSource() == chkRed) circle.setForeground(Color.red); else if (e.getSource() == chkYellow) circle.setForeground(Color.yellow); else if (e.getSource() == chkFilled || e.getSource() == chkCentered || e.getSource() == chkBlack) { circle.filled = chkFilled.getState(); circle.inTheCenter = chkCentered.getState(); circle.blackBackground = chkBlack.getState(); } circle.repaint(); }}

  38. Choice and List • Choice chooses one item only while List allows for multiple selections at once. • Declarations: Choice colors = new Choice(); colors.add(“Blue”); colors.add(“Red”); colors.add(“Yellow”); List l = new list(3,true); //three items in list, all can be selected at once l.add(“Filled”); l.add(“In the center”); l.add(“Black Background”);

  39. Choice and List Methods • x.add(“text”); Adds option text to x. • x.select(n); selects option n in x. • x.isIndexSelected(n); returns bool value • Connecting a listener: X.addItemListener(l); public void itemStateChanged(ItemEvent e) { //We get here when an option is selected or deselected.} e.getSource(); returns the object where the event occurred.

  40. Choice & List Example: import java.awt.*; import java.awt.event.*; import java.applet.*; public class CircleChoiceListDemo extends Applet implements ItemListener { private CircleCanvas circle = new CircleCanvas(); private Panel panel = new Panel(); private Choice choColors = new Choice(); private List lstList = new List(3, true); // multi-select able public void init() { circle.setForeground(Color.green); setLayout( new GridLayout(2, 1) ); add(circle); add(panel); panel.setLayout( new GridLayout(1, 2) ); panel.add(choColors); // add the items to the choice menu choColors.add("Blue"); choColors.add("Red"); choColors.add("Yellow"); // select the first item choColors.select(0); panel.add(lstList);

  41. Choice & List Example: // add the item to the list lstList.add("Filled"); lstList.add("Centered"); lstList.add("Black Background"); // select the first two items lstList.select(0); lstList.select(1); // connect the listeners choColors.addItemListener(this); lstList.addItemListener(this); // make visible setVisible(true); } public void itemStateChanged(ItemEvent e) {// listener if (e.getSource() == choColors) { if (choColors.getSelectedIndex() == 0) circle.setForeground(Color.blue); else if (choColors.getSelectedIndex() == 1) circle.setForeground(Color.red); else circle.setForeground(Color.yellow); } else if (e.getSource() == lstList) { circle.filled = lstList.isIndexSelected(0); circle.inTheCenter = lstList.isIndexSelected(1); circle.blackBackground = lstList.isIndexSelected(2); } circle.repaint(); } }

  42. Choice & List Example:

  43. Scrollbar • Allows for ‘slider’ input • Declaration: • Scrollbar sR = new Scrollbar(position, init.value, scrollbox, min.value, max.value); • Position is either Scrollbar.HORIZONTAL or Scrollbar.VERTICAL. • Scrollbox is size of the moveable box

  44. Scrollbar Methods • setUnitIncrement(n); changes the amount of space moved when arrow is clicked by ±n • setPageIncrement(n); changes the amount of space moved when inside the bar is clicked by ±n • setValue(n); sets the value at scrollbox’s left/lower edge • getValue(n); gets the value at scrollbox’s left/lower edge • Listening: uses AdjustmentListener object instantiated as seen in Choice/List. Uses getSource();

  45. Scrollbar Example: import java.awt.*; import java.awt.event.*; import java.applet.*; public class CircleScrollbarDemo extends Applet implements AdjustmentListener { private CircleCanvas circle = new CircleCanvas(); private Panel panel = new Panel(); private Scrollbar sbRed = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); private Scrollbar sbGreen = new Scrollbar(Scrollbar.HORIZONTAL, 255, 1, 0, 256); private Scrollbar sbBlue = new Scrollbar(Scrollbar.HORIZONTAL, 0, 1, 0, 256); private Label lblRed = new Label("0", Label.CENTER); private Label lblGreen = new Label("255", Label.CENTER); private Label lblBlue = new Label("0", Label.CENTER);

  46. Scrollbar Example public void init() { circle.setForeground(Color.green); setLayout( new GridLayout(2, 1, 0, 5) ); add(circle); add(panel); panel.setLayout( new GridLayout(3, 3) ); panel.add( new Label("Red", Label.CENTER) ); panel.add(sbRed); panel.add(lblRed); panel.add( new Label("Green", Label.CENTER) ); panel.add(sbGreen); panel.add(lblGreen); panel.add( new Label("Blue", Label.CENTER) ); panel.add(sbBlue); panel.add(lblBlue); sbRed.addAdjustmentListener(this); sbGreen.addAdjustmentListener(this); sbBlue.addAdjustmentListener(this); setVisible(true); }

  47. Scrollbar Example: public void adjustmentValueChanged(AdjustmentEvent e) { if (e.getSource() == sbRed || e.getSource() == sbGreen || e.getSource() == sbBlue) { int red = sbRed.getValue(), green = sbGreen.getValue(), blue = sbBlue.getValue(); lblRed.setText( String.valueOf(red) ); lblGreen.setText( String.valueOf(green) ); lblBlue.setText( String.valueOf(blue) ); circle.setForeground( new Color(red, green, blue) ); circle.repaint(); } } }

  48. Text Input • TextField -- one line, or row, of text • TextArea -- multiple rows

  49. TextField Methods • Declarations: • TextField t = new TextField(); • TextField t = new TextField(n); n sets space • TextField t = new TextField(“text”); • TextField t = new TextField(“text, n); • Uses ActionListener • e.getSource(); • x.getText(); Returns the text in the box as a String (which must be parsed for numeric data)

  50. TextField Methods • setColumns(n) -- Changes the size • setText(“text”) • setEchoChar(‘*’) -- Displays in place of entered text. Used for password fields. • selectAll() • select(i, j) -- Selects characters i to j • getSelectedText

More Related