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
38
Embed
Using Inheritance to Customize Frames Use inheritance for complex frames to make programs easier to understand Design a subclass of JFrame Store the components.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
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
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
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
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…
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)
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);
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);
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 !!
// 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();
}
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);
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
}
}
// 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();
}
}
Colors3.java
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() )
. . .
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!!
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.
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();
//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");
//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;
}
JPanel temp = new JPanel(); //set up panel
temp.setBackground(Color.blue);
temp.add(cbox);
temp.add(outbox);
return temp;
}
Text Areas
Figure 8:The TextAreaViewer Application
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…
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
Text Areas
To add scroll bars to a text area:
JTextArea textArea = new JTextArea(ROWS, COLUMNS); JScrollPane scrollPane = new JScrollPane(textArea);
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
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
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 ());