Using Inheritance to Customize Frames Use inheritance for

  • Slides: 38
Download presentation
Using Inheritance to Customize Frames • Use inheritance for complex frames to make programs

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

Example (files on website): Colors. java - simple GUI Colors 2. java - same

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

Layout Management • Up to now, we have had limited control over layout of

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 Layout. Manager interface (so they are of type Layout. Manager) • A container type class (JPanel, etc) provides a set. Layout(Layout. Manager), which changes the layout of that container object

Flow Layout • The Flow. JPanel uses the Flow. Layout. Manager by default. •

Flow Layout • The Flow. JPanel uses the Flow. Layout. Manager 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…

Flow Layout continued Flow. Layout Constructors Flow. Layout (alignment) * alignment can be specified

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

Border Layout • Border layout groups container into five areas: center, north, west, south

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

Border Layout • Default layout manager for a Jframe (technically, the frame's content pane)

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): panel. set. Layout(new Border. Layout()); panel. add(component, Border. Layout. NORTH); • 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.

Grid Layout • Arranges components in a grid with a fixed number of rows

Grid Layout • Arranges components in a grid with a fixed number of rows and columns • Resizes each component so that they all have same size • Expands each component to fill the entire allotted area • Add the components, row by row, left to right: JPanel number. Panel = new JPanel(); number. Panel. set. Layout(new Grid. Layout(4, 3)); number. Panel. add(button 7); number. Panel. add(button 8); number. Panel. add(button 9); number. Panel. add(button 4); . . .

Grid Layout Figure 2: The Grid Layout

Grid Layout Figure 2: The Grid Layout

Choices • Radio buttons • Check boxes • Combo boxes A Combo Box, Check

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

Radio Buttons • User can click radio buttons, just like other buttons BUT Radio

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 Button. Group object. The Button. Group turns 1 button off when the next one is turned on • s. Button = new JRadio. Button("Small"); m. Button = new JRadio. Button("Medium"); l. Button = new JRadio. Button("Large"); Button. Group group = new Button. Group(); group. add(sbutton); group. add(mbutton); group. add(lbutton);

Radio Buttons continued • The Button. Group is a logical component, NOT a visual

Radio Buttons continued • The Button. Group 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: s. Button. set. Selected(true); The buttons still need to be placed into a panel individually. panel. add(s. Button); panel. add(m. Button); panel. add(l. Button);

Radio Buttons continued Your code can tell if a Radio. Button is selected if

Radio Buttons continued Your code can tell if a Radio. Button is selected if (s. Button. is. Selected()). . . One usually wants to check which button is selected WHEN THE USER HAS clicked on ONE!! An Action. Event is created when the user clicks on one of the buttons. . so this code is in an Action. Listener !!

// Frame which allows the user to select it’s background color import javax. swing.

// 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. Border. Layout; public class Rad. Demo extends JFrame { public Rad. Demo(){ createpanel(); pack(); } //set up panel

public void createpanel() { //set up button and put in panel final JRadio. Button

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

redbtn. set. Selected(true); //default button/color is red btnpanel. set. Background(Color. RED); class Btn. Listen

redbtn. set. Selected(true); //default button/color is red btnpanel. set. Background(Color. RED); class Btn. Listen implements Action. Listener{ //define listener class public void action. Performed (Action. Event e) { if (redbtn. is. Selected() ) btnpanel. set. Background(Color. RED); else if (bluebtn. is. Selected() ) btnpanel. set. Background(Color. BLUE); else btnpanel. set. Background(Color. GREEN); } } Btn. Listen blisten = new Btn. Listen(); //create and register listener object redbtn. add. Action. Listener(blisten); bluebtn. add. Action. Listener(blisten); greenbtn. add. Action. Listener(blisten);

// main to create and show frame public class Color. Panel{ public static void

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

Check Boxes Similar to radio button, BUT not usually mutually exclusive JCheck. Box it

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

Combo Boxes Combination of selection and text field Create JCombo. Box object, then ‘add’

Combo Boxes Combination of selection and text field Create JCombo. Box object, then ‘add’ the items JCombo. Box face. Name = new JCombo. Box(); face. Name. add. Item("Serif"); face. Name. add. Item("Sans. Serif"); . . . (Any object type can be added to Combo. Box --to. String determines what is displayed!!

Combo Boxes To initialize the Combo. Box selection: facename. set. Selected. Item(“Italics”); To get

Combo Boxes To initialize the Combo. Box selection: facename. set. Selected. Item(“Italics”); To get user selection: sel= (String)face. Name. get. Selected. Item(); if (sel. equals(“Bold”)) ………………. . Note: Cast needed because return type is Object !! An Action. Event is created by a Combo. Box if the user makes a choice!! So you need to create an Action. Listener class and install it on Combo. Box object.

Combo Box items are ‘indexed’. . Values stored in a Combo. BOx are internally

Combo Box items are ‘indexed’. . Values stored in a Combo. BOx are internally ‘indexed’ beginning at 0. Can work with the objects using their indices as well Another way to initialize the Combo. Box selection: facename. set. Selected. Index(0); Accordingly, can get user selection: int ind = face. Name. get. Selected. Index();

//method returns a panel with a combo box on it public JPanel makebottom() {

//method returns a panel with a combo box on it public JPanel makebottom() { final JText. Field outbox = new JText. Field(" $15. 00", 10); //set up combo box and add a listener final JCombo. Box cbox = new JCombo. Box(); cbox. add. Item("Large Price"); cbox. add. Item("Medium Price"); cbox. add. Item("Small Price"); cbox. set. Selected. Item("Large Price");

//method continues //set up listener class Box. Listener implements Action. Listener{ public void action.

//method continues //set up listener class Box. Listener implements Action. Listener{ public void action. Performed(Action. Event e){ if (cbox. get. Selected. Item(). equals("Large Price")) outbox. set. Text("$15. 00"); else if (cbox. get. Selected. Item(). equals("Medium Price")) outbox. set. Text("$10. 00"); else outbox. set. Text("$8. 00"); } } Box. Listener clisten = new Box. Listener(); cbox. add. Action. Listener(clisten); JPanel temp = new JPanel(); //set up panel temp. set. Background(Color. blue); temp. add(cbox); temp. add(outbox);

JPanel temp = new JPanel(); temp. set. Background(Color. blue); temp. add(cbox); temp. add(outbox); return

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

Text Areas Figure 8: The Text. Area. Viewer Application

Text Areas Figure 8: The Text. Area. Viewer Application

Text Areas • Use a JText. Area to show multiple lines of text •

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

Text Areas • Use newline characters to separate lines: text. Area. append(account. get. Balance()

Text Areas • Use newline characters to separate lines: text. Area. append(account. get. Balance() + "n"); • To use for display purposes only: text. Area. set. Editable(false); // program can call set. Text and append to change it

Text Areas To add scroll bars to a text area: JText. Area text. Area

Text Areas To add scroll bars to a text area: JText. Area text. Area = new JText. Area(ROWS, COLUMNS); JScroll. Pane scroll. Pane = new JScroll. Pane(text. Area);

Sliders Where as a Combo box lets the users choose from a discrete set

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.

Sliders Constructors JSlider (int min, int max, int init. Val) JSlider( int orientation, int

Sliders Constructors JSlider (int min, int max, int init. Val) JSlider( int orientation, int min, int max) JSlider (int min, int max) Visuals: set. Major. Tick. Spacing(int n) set. Minor. TIck. Spacing((int n) set. Paint. Ticks(boolean val) set. Paint. Labels (boolean val); Events: * when slider moves, the value of slider moves between min and max * when value changes, a Change. Event happens * listeners must implement the Change. Listener interface * this interface contains one method: void state. Changed(Change. Event e) * slider method int get. Value() provides slider value

Borders • Place a border around a panel to group its contents visually •

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

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

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

Advanced Topic: Layout Management • Step 2: Find groupings of adjacent components with the

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

Advanced Topic: Layout Management • Step 3: Identify layouts for each group • Step

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

Menus Pull-Down Menus

Menus Pull-Down Menus

Swing provides pull-down menus • To build a menu: Create a menu bar JMenu.

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

EXAMPLE (runnable code in Menu. Color. java) JMenu. Bar mbar = new JMenu. Bar();

EXAMPLE (runnable code in Menu. Color. java) JMenu. Bar mbar = new JMenu. Bar(); //create menu bar fr. set. JMenu. Bar(mbar); //add to frame JMenu opt. Menu = new JMenu("Options"); //new menu mbar. add(opt. Menu); // add to menu bar //create and set up 2 items JMenu. Item cpan = new JMenu. Item("Color panel"); CPListen cpl = new CPListen(); //CPListen is Action. Listener class cpan. add. Action. Listener(cpl); opt. Menu. add(cpan); JMenu. Item calpan = new JMenu. Item("Calorie burn"); Cal. PListen calpl = new Cal. PListen(); //Cal. PListen is Action. Listener class calpan. add. Action. Listener(calpl); opt. Menu. add(calpan);