1 / 38

Using Inheritance to Customize Frames

Using Inheritance to Customize Frames. Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components as instance fields Initialize them in the constructor of your subclass

yael
Download Presentation

Using Inheritance to Customize Frames

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. Using Inheritance to Customize Frames • Use inheritance for complex frames to make programs easier to understand • Design a subclass of JFrame • Store the components as instance fields • Initialize them in the constructor of your subclass • If initialization code gets complex, simply add some helper methods

  2. Example (files on website): Colors.java - simple GUI Colors2.java - same application written as JFrame class Colors3.java - helper methods added Try running ColorApp --- notice that this main program provides 3 Color button frames Vapp3.java - GUI w/ three panels written as JFrame class

  3. Layout Management • Up to now, we have had limited control over layout of components • Each container uses a layout manager to direct the arrangement of its components • All layout managers implement the LayoutManager interface (so they are of type LayoutManager) • A container type class (JPanel, etc) provides a setLayout(LayoutManager), which changes the layout of that container object

  4. Flow Layout • The FlowJPanel uses the FlowLayoutManager by default. • The flow layout manager lines the components horizontally until there is no more room and then starts a new row of components. • When the user resizes the container, the layout manager automatically reflows the components to fill the available space. • By default, components are centered in a row, but a left or right alignment can be set when constructing a flow layout manager. Continued…

  5. Flow Layout continued FlowLayout Constructors FlowLayout (alignment) * alignment can be specified by a static FlowLayout field For example: panel.setLayout(new FlowLayout(FlowLayout.LEFT)); FlowLayout (alignment, int horizontalgap, int verticalgap) * gaps indicate # of pixels between components For example: panel.setLayout(new FlowLayout(FlowLayout.LEFT,10,10)

  6. Border Layout • Border layout groups container into five areas: center, north, west, south and east Components Expand to Fill Space in the Border Layout

  7. Border Layout • Default layout manager for a Jframe (technically, the frame's content pane) • Border layout lets you choose where to add a component by specifing the position like this (center is default): • Expands each component to fill the entire allotted area Typically a panel is placed inside each area, to control the Layout for those components. • The edge components are laid out first, with the remaining space occupied by the center. • Resizing changes the center size, not the edge. panel.setLayout(new BorderLayout()); panel.add(component, BorderLayout.NORTH);

  8. Grid Layout • Arranges components in a grid with a fixed number of rows and columns • Resizes each component so that they all have samesize • Expands each component to fill the entire allotted area • Add the components, row by row, left to right: JPanel numberPanel = new JPanel(); numberPanel.setLayout(new GridLayout(4, 3)); numberPanel.add(button7); numberPanel.add(button8); numberPanel.add(button9); numberPanel.add(button4); . . .

  9. Grid Layout Figure 2:The Grid Layout

  10. Choices • Radio buttons • Check boxes • Combo boxes A Combo Box, Check Box, and Radio Buttons

  11. Radio Buttons • User can click radio buttons, just like other buttons BUT Radio buttons are mutually exclusive • This is achieved by placing all associated buttons in a ButtonGroup object. The ButtonGroup turns 1 button off when the next one is turned on • sButton = new JRadioButton("Small");mButton = new JRadioButton("Medium"); lButton = new JRadioButton("Large");ButtonGroup group = new ButtonGroup();group.add(sbutton);group.add(mbutton);group.add(lbutton);

  12. Radio Buttons continued • The ButtonGroup is a logical component, NOT a visual component. (You don’t place it into a panel) • It is good practice to initialize one of the buttons to ON: sButton.setSelected(true); The buttons still need to be placed into a panel individually. panel.add(sButton); panel.add(mButton); panel.add(lButton);

  13. Radio Buttons continued Your code can tell if a RadioButton is selected if (sButton.isSelected()) . . . One usually wants to check which button is selected WHEN THE USER HAS clicked on ONE!! An ActionEvent is created when the user clicks on one of the buttons .. so this code is in an ActionListener !!

  14. // Frame which allows the user to select it’s background color import javax.swing.*; import java.awt.event.*; import java.awt.Color; import java.awt.BorderLayout; public class RadDemo extends JFrame { public RadDemo(){ createpanel(); //set up panel pack(); }

  15. public void createpanel() { //set up button and put in panel final JRadioButton redbtn = new JRadioButton("RED"); final JRadioButton bluebtn = new JRadioButton("BLUE"); final JRadioButton greenbtn = new JRadioButton("GREEN"); ButtonGroup grp = new ButtonGroup(); grp.add(redbtn); grp.add(bluebtn); grp.add(greenbtn); final JPanel btnpanel = new JPanel(); //put on panel btnpanel.add(redbtn); btnpanel.add(bluebtn); btnpanel.add(greenbtn);

  16. redbtn.setSelected(true); //default button/color is red btnpanel.setBackground(Color.RED); class BtnListen implements ActionListener{ //define listener class public void actionPerformed (ActionEvent e) { if (redbtn.isSelected() ) btnpanel.setBackground(Color.RED); else if (bluebtn.isSelected() ) btnpanel.setBackground(Color.BLUE); else btnpanel.setBackground(Color.GREEN); } } BtnListen blisten = new BtnListen(); //create and register listener object redbtn.addActionListener(blisten); bluebtn.addActionListener(blisten); greenbtn.addActionListener(blisten); getContentPane().add(btnpanel, BorderLayout.CENTER); //put on frame } }

  17. // main to create and show frame public class ColorPanel{ public static void main (String [] args) { //create and test one of these frames JFrame newframe = new RadDemo(); newframe.show(); } }

  18. Check Boxes Similar to radio button, BUT not usually mutually exclusive JCheckBox it = new JCheckBox("Italic"); JCheckBox bld = new JCheckBox(“Bold”); No need for button group --- if you put them in a ButtonGroup they will be mutually exclusive!! in Action listener …….. If (bld.isSelected() ) . . .

  19. Combo Boxes Combination of selection and text field Create JComboBox object, then ‘add’ the items JComboBox faceName = new JComboBox();faceName.addItem("Serif");faceName.addItem("SansSerif");. . . (Any object type can be added to ComboBox --toString determines what is displayed!!

  20. Combo Boxes To initialize the ComboBox selection: facename.setSelectedItem(“Italics”); To get user selection: sel= (String)faceName.getSelectedItem(); if (sel.equals(“Bold”)) ……………….. Note:Cast needed because return type is Object !! An ActionEvent is created by a ComboBox if the user makes a choice!! So you need to create an ActionListener class and install it on ComboBox object.

  21. Combo Box items are ‘indexed’ .. Values stored in a ComboBOx are internally ‘indexed’ beginning at 0 . Can work with the objects using their indices as well Another way to initialize the ComboBox selection: facename.setSelectedIndex(0); Accordingly, can get user selection:int ind = faceName.getSelectedIndex();

  22. //method returns a panel with a combo box on it public JPanel makebottom() { final JTextField outbox = new JTextField(" $15.00", 10); //set up combo box and add a listener final JComboBox cbox = new JComboBox(); cbox.addItem("Large Price"); cbox.addItem("Medium Price"); cbox.addItem("Small Price"); cbox.setSelectedItem("Large Price");

  23. //method continues //set up listener class BoxListener implements ActionListener{ public void actionPerformed(ActionEvent e){ if (cbox.getSelectedItem().equals("Large Price")) outbox.setText("$15.00"); else if (cbox.getSelectedItem().equals("Medium Price")) outbox.setText("$10.00"); else outbox.setText("$8.00"); } } BoxListener clisten = new BoxListener(); cbox.addActionListener(clisten); JPanel temp = new JPanel(); //set up panel temp.setBackground(Color.blue); temp.add(cbox); temp.add(outbox); return temp; }

  24. JPanel temp = new JPanel(); //set up panel temp.setBackground(Color.blue); temp.add(cbox); temp.add(outbox); return temp; }

  25. Text Areas Figure 8:The TextAreaViewer Application

  26. Text Areas • Use a JTextArea to show multiple lines of text • You can specify the number of rows and columns: • setText: to set the text of a text field or text area • append: to add text to the end of a text area final int ROWS = 10; final int COLUMNS = 30; JTextArea textArea = new JTextArea(ROWS, COLUMNS); Continued…

  27. Text Areas • Use newline characters to separate lines: • To use for display purposes only: textArea.append(account.getBalance() + "\n"); textArea.setEditable(false); // program can call setText and append to change it

  28. Text Areas To add scroll bars to a text area: JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);

  29. Sliders Where as a Combo box lets the users choose from a discrete set of values, a slider offers a choice of a value from within a range.

  30. Sliders Constructors JSlider (int min, int max, int initVal) JSlider( int orientation, int min, int max) JSlider (int min, int max) Visuals: setMajorTickSpacing(int n) setMinorTIckSpacing((int n) setPaintTicks(boolean val) setPaintLabels (boolean val); Events: * when slider moves, the value of slider moves between min and max * when value changes, a ChangeEvent happens * listeners must implement the ChangeListener interface * this interface contains one method: void stateChanged(ChangeEvent e) * slider method int getValue() provides slider value

  31. Borders • Place a border around a panel to group its contents visually • EtchedBorder: theree-dimensional etched effect • Can add a border to any component, but most commonly to panels: • TitledBorder: a border with a title Jpanel panel = new JPanel ();panel.setBorder(new EtchedBorder ()); panel.setBorder(new TitledBorder(new EtchedBorder(), “Size”));

  32. Advanced Topic: Layout Management • Step 1: Make a sketch of your desired component layout

  33. Advanced Topic: Layout Management • Step 2: Find groupings of adjacent components with the same layout

  34. Advanced Topic: Layout Management • Step 3: Identify layouts for each group • Step 4: Group the groups together • Step 5: Write the code to generate the layout

  35. Menus Pull-Down Menus

  36. Swing provides pull-down menus • To build a menu: Create a menu bar JMenuBar object Add the menu bar to a frame use JFrame method setJMenuBar Create each menu and add it to menubar JMenu object represents menu use JMenuBar method add Add menu items to the menu JMenuItem object represents menu item use JMenu method add Install Action Listeners to JMenuItem objects useJMenuItem addActionListener methods Add action listeners only to menu items, not to menus or the menu bar

  37. EXAMPLE (runnable code in MenuColor.java) JMenuBar mbar = new JMenuBar(); //create menu bar fr. setJMenuBar(mbar); //add to frame JMenu optMenu = new JMenu("Options"); //new menu mbar.add(optMenu); // add to menu bar //create and set up 2 items JMenuItem cpan = new JMenuItem("Color panel"); CPListen cpl = new CPListen(); //CPListen is ActionListener class cpan.addActionListener(cpl); optMenu.add(cpan); JMenuItem calpan = new JMenuItem("Calorie burn"); CalPListen calpl = new CalPListen(); //CalPListen is ActionListener class calpan.addActionListener(calpl); optMenu.add(calpan);

More Related