• No results found

Understanding Swing Components

N/A
N/A
Protected

Academic year: 2021

Share "Understanding Swing Components"

Copied!
59
0
0

Loading.... (view fulltext now)

Full text

(1)

Understanding Swing Components

Outline:

Use the JFrame class

Extend the JFrame class

Use the JPanel class

Understand Swing Event Listener

Use the JCheckbox class

Use the ButtonGroup class

Use the JComboBox class

Create JScrollPanes

1

(2)

Using the JFrame Class

It has four constructors:

• JFrame() – constructs a new frame that initially is invisible and has no title.

• JFrame(String title) – creates a new, initially invisible JFrame with the specified title.

• JFrame(GraphicsConfiguration gc) – creates a JFrame in the specified GraphicsConfiguration of a screen device and a blank title.

• JFrame(String title, GraphicsConfiguration gc) – creates a JFrame with the specified title and the specified GraphicsConfiguration of a screen.

(3)

Example:

JFrame firstFrame = new JFrame(“Hello”);

JFrame firstFrame = new JFrame();

• After you create a JFrame object, you can use the now-familiar object-dot-method format you have used with other objects to call methods that manipulate a JFrame’s features.

3

(4)

Useful methods inherited by the JFrame class

• void setTitle(String)

• void setsize(Dimension)

• String getTitle()

• void setResizable(boolean)

• Boolean isResizable()

• void setVisible(boolean)

• void setBounds(int, int, int, int): overrides the default behavior of the JFrame to be positioned in the upper-left corner.

(5)

Example:

- firstFrame.setSize(200,100);

- firstFrame.setTitle(“My frame”);

5

(6)

To Create a JFrame Object

• Open a new file in your text editor.

• Import the java.swing classes: import javax.swing.*;

• On the next line, type the following class header for the JDemoFrame class and its opening curly brace:

public class JDemoFrame {

• On the next line type the following main() method header:

public static void main(String[] args) {

JFrame aFrame = new JFrame(“This is a Frame”);

aFrame.setSize(200, 250);

aFrame.setVisible(true);

} }

• Save the file as JDemoFrame.java 6

(7)

NOTE:

• When a user closes a JFrame, the default behavior is for the JFrame to become hidden and the application to keep running.

• If you want the program to exit when the user clicks close.

- To change this behavior, you can call a JFrame’s setDefaultCloseOperation() method and use one of the following four values as an argument:

7

(8)

• JFrame.EXIT_ON_CLOSE – exit program when JFrame is closed.

• WindowConstants.DISPOSE_ON_CLOSE – close the frame, dispose of the JFrame object, and keep running the application.

• WindowConstants.DO_NOTHING_ON_CLOSE – keep the JFrame and continue running in other words, disable the Close button.

• WindowConstants.HIDE_ON_CLOSE – Close the JFrame and continue running; this is the default operation.

(9)

To modify the application so it ends when the user clicks the JDemoFrame Close button.

• Within the JDemoFrame program file, change the class name to JDemoFrameThatCloses.

• Add the following as last executable stmt within the main() method:

aFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

• Save it and compile.

9

(10)

Extending the JFRAME Class

• You can instantiate a simple JFrame object within a main() or any other method of any class you write.

(11)

The JMyFrame Program

import javax.swing.*;

public class JMyFrame extends JFrame {

public JMyFrame() {

super("This is My Frame");

setSize(400,120);

setVisible(true);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

public static void main(String[] args) {

JMyFrame myFrame = new JMyFrame();

JMyFrame mySecondFrame = new JMyFrame();

}

} 11

(12)

Using The JPanel Class(1)

• This is the simplest Swing container – JPanel – it is a plain, borderless surface that can hold GUI components.

• Every JPanel is a Container; you use a JPanel to hold other GUI components like Jbutton, JCheckBox, or even other JPanel.

(13)

Using The JPanel Class(2)

• To add a component to a JPanel, you call the container’s add() method, using the component as the argument.

• When you use a JPanel to hold components, you also must use the setContentPane() method to allow the JPanel to be set as a content pane so it can hold components.

13

(14)

Using The JPanel Class(3)

• Example:

Jbutton exitButton = new Jbutton (“Exit”);

Jpanel myPanel = new Jpanel();

myPanel.add(exitButton);

setContentPane(myPanel);

• It creates a Jbutton and adds it to a JPanel named myPanel.

(15)

To create a JFrame that displays three Jbuttons within a JPanel

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JPanelAndButtons extends JFrame {

Jbutton b1 = new Jbutton(“One”);

Jbutton b2 = new Jbutton(“Two”);

Jbutton b3 = new Jbutton(“Three”);

• In the JPanelAndButton constructor method, set the JFrame title to “Panel with Buttons” and the default close operation to exit the program when the JFrame is closed.

• Create a JPanel, add the three buttons to it, and then set the content pane.

15

(16)

public JPanelAndButtons() {

super(“Panel with Buttons”);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Jpanel pane = new Jpanel();

pane.add(b1);

pane.add(b2);

pane.add(b3);

setContentPane(pane);

}

• Add the following main() method that creates a new JFrame named aFrame, size it using the setSize() method and then set its visible property to true.

public static void main(String[] arguments) {

Jframe aFrame = new JPanelAndButtons();

aFrame.setSize(250,100);

aFrame.setVisible(true);

} }

• Save it as JPanelAndButtons.java

(17)

Understanding Swing Event Listeners

• Classes that respond to user-initiated events, like button clicks, must implement an interface that deals with, or handles, the events.

• The interfaces are called event listeners, and you first learned about when you used the ActionListener interface with Jbutton objects.

17

(18)

Some Event Listeners

Listener Type of events Example

ActionListener Action events Button click

AdjustmentListener Adjustment events Scrollbar moves

ChangeListener Change events Slider is repositioned

FocusListener Keyboard focus events Textfield gain or loses focus

ItemListener Item events Check box changes status

KeyListener Keyboard events Text is entered

MouseListener Mouse events Mouse click

MouseMotionListener Mouse movement events Mouse rolls

WindowListener Window events Window closes

(19)

The format is:

theSourceOfTheEvent.addListenerMethod(theClassThatShouldRespond);

Example:

• when you want a JCheckBox to respond to a user’s clicks, you can use the addItemListener() method to register the JCheckBox as the type of object that can create an ItemEvent.

• The argument you place within the parentheses of the call to the addItemListener() method is the object that should respond to the event

– perhaps a JApplet or a JFrame that contains the JCheckBox that generates the event.

19

(20)

Some Swing Components and their Associated Listener-Registering Methods

Components Associated Listener-Registering Method JButton, JCheckBox, JComboBox,

JTextField and JRadioButton

addActionListener()

JScrollBar addAdjustmentListener()

All Swing Components addFocusListener(), addKeyListener(),

addMouseListener() and addMouseMotionListener() Jbutton, JCheckBox, JComboBox and

JRadioButton

addItemListener()

All JWindow and JFrame component addWindowListener()

JSlider, JCheckBox addChangeListener()

(21)

Selected Methods that respond to Events (1)

Listener Method

ActionListener actionPerformed(ActionEvent)

AdjustmentListener adjustmentValueChanged(AdjustmentEvent) FocusListener focusGained(FocusEvent)

focusLost(FocusEvent)

ItemListener itemStateChanged(ItemEvent)

21

(22)

Methods that respond to Events (2)

• When you declare a class that will handle an event, you create the class to either implement a listener interface or to extend a class that implements a listener interface.

Example:

• If a Jframe named MyFrame needs to respond to a user’s clicks on a JCheckBox, you write the following class header:

public class MyFrame extends Jframe implements ItemListener

(23)

Methods that respond to Events (3)

• Register an instance of the event handler class as a listener for one or more components.

• For example, if MyFrame contains a JCheckBox named myCheckBox, then you would code:

myCheckBox.addItemListener(this);

• Where this refers to the class in which myCheckBox is declared – in this case MyFrame.

23

(24)

Methods that respond to Events (4)

• Write a method that accepts the generated event and reacts to it.

For example:

public void itemStateChanged(ItemEvent event) {

//code that executes whenever the event occurs

}

(25)

Methods that respond to Events (5)

• You can use the getSource() method to determine the component that sent the event.

Example:

• The following actionPerformed() method gets the source of the event, and then compares it to a Jbutton named oneButton, which takes one action if the Jbutton is the source of the event, and a different action if some other component is the source of the event.

25

(26)

Methods that respond to Events (6)

public void actionPerformed(ActionEvent event) {

Object source = event.getSource();

if (source == oneButton) // take some action else

//take some other action

(27)

To create an application with functional JButtons

• Open the JPanelAndButtons.java file.

• Save it as JChangeButtonMessage.java.

• Change the class name to JChangeButtonMessage to match the new filename. Also change both the constructor method header and the constructor call used to create the aFrame object within the main() method so that each matches the new class name. Within the constructor method, change the string argument to the super() method from “Panel with Buttons” to “Change Message.”

• At the end of the JChangeButtonMessage class header, after extends Jframe, add implements ActionListener so that the class can respond to ActionEvents.

27

(28)

• Register the JChangeButtonMessage class as a listener for events generated by the three buttons by adding the following three stmts at the end of, but within, the JChangeButtonMessage() constructor method:

b1.addActionListener(this);

b2.addActionListener(this);

b3.addActionListener(this);

• public void actionPerformed(ActionEvent e) {

object source = e.getSource();

if (source == b1)

b1.setText(“Event”);

else if(source == b2)

b2.setText(“Handlers”);

else if(source == b3)

b3.setText(“Incorporated”);

}

• Save the Program, then compile and execute it.

28

(29)

Using the JCheckBox Class

Methods Purpose

void setText(String) Set the text for the JCheckBox string getText() Return the JCheckBox text

void setSelected(boolean) Set the state of the JCheckBox to true for selected or false for unselected

boolean isSelected Gets the current state (checked or unchecked) of the JCheckBox

29

(30)

To write a Swing Application that includes three JCheckBox object used to determine an event’s price

• As a software developer at ABC Soft Ltd. You are required to create an interaction program that Event Handlers Incorporated clients can use to determine an event’s price. The base price of an event is

$300 and there are several options a user can choose. Holding the event on a weekend adds $100 to the price, hosting over 200 guests adds $200 and including live entertainment adds $400. A guest can select none, some, or all of these premium additions. Each time the user changes the option package, the event price is recalculated.

(31)

Open a new file in your text editor and save as JCheckBoxDemo and then type the following:

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JCheckBoxDemo extends JFrame implements ItemListener {

Declare the variables that hold the base price etc.:

int basePrice = 300;

int weekendPremium = 100;

int guestPremium = 200;

int entertainPremium = 400;

int totalPrice = basePrice;

Declare three JCheckBox object:

JCheckBox weekendBox = new JCheckBox("Weekend premium $" + weekendPremium,false);

JCheckBox guestBox = new JCheckBox("Over 200 guests $" + guestPremium,false);

JCheckBox entertainBox = new JCheckBox("Live entertainment $" +

entertainPremium,false); 31

(32)

Include JLabels to hold user instructions and information and a JTextField in which to display the total price:

JLabel eventHandlersLabel = new JLabel("Event Handlers Incorporated");

JLabel ePrice = new JLabel("The price for your event is");

JTextField totPrice = new JTextField(10);

JLabel optionExplainLabel = new JLabel("Base price for an event is $" + basePrice + ".");

JLabel eventExplainLabel2 = new JLabel("Check the options you want.");

Begin the JCheckBoxDemo class constructor:

public JCheckBoxDemo() {

super("Event Price Estimator");

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();

pane.add(eventHandlersLabel);

pane.add(optionExplainLabel);

pane.add(eventExplainLabel2);

pane.add(weekendBox);

pane.add(guestBox);

pane.add(entertainBox);

pane.add(ePrice);

pane.add(totPrice);

(33)

Continue the constructor by setting the text of the totPrice JTextField to display a dollar sign and the totalPrice value:

totPrice.setText("$" + totalPrice);

weekendBox.addItemListener(this);

guestBox.addItemListener(this);

entertainBox.addItemListener(this);

setContentPane(pane);

}

Add a main() method that creates an instance of the Jframe and sets its size and visibility:

public static void main(String[] args) {

JFrame aFrame = new JCheckBoxDemo();

aFrame.setSize(300,250);

aFrame.setVisible(true);

}

33

(34)

Begin the itemStateChanged() method that executes when the user selects or deselects a JCheckBox:

public void itemStateChanged(ItemEvent event) {

Object source = event.getSource();

int select = event.getStateChange();

Conclude the code on Next slide

(35)

Write a nested if stmt that tests whether the source is equivalent to the weekendBox, guestBox, or by default, the entertainBox:

if(source == weekendBox)

if(select == ItemEvent.SELECTED) totalPrice += weekendPremium;

else

totalPrice -= weekendPremium;

else if(source == guestBox)

{

if(select == ItemEvent.SELECTED) totalPrice += guestPremium;

else

totalPrice -= guestPremium;

}

else

if(select == ItemEvent.SELECTED) totalPrice += entertainPremium;

else

totalPrice -= entertainPremium;

totPrice.setText("$" + totalPrice);

}

} 35

(36)

Project_2

• Create an application that contains a ButtonGroup.

Event Handlers Incorporated has decided to base event prices strictly on the number of guests: $1300,

$2400, or $6000 for groups of 1-100, 101-200 or over 200 respectively. The user must choose a guest number category to see an event’s price. A ButtonGroup is appropriate because the options are mutually exclusive; you would not want a user to be able to select two or three categories.

(37)

Using The ButtonGroup Class

• To create a ButtonGroup and then add a JCheckBox, you must perform three steps:

• Create a ButtonGroup, such as:

ButtonGroup aGroup = new ButtonGroup();

• Create a JCheckBox such as:

JCheckBox aBox = new CheckBox();

• Add aBox to aGroup with:

aGroup.add(aBox);

37

(38)

• Create an application that contains a ButtonGroup. Event Handlers Incorporated has decided to base event prices strictly on the number of guests: $1300, $2400, or $6000 for groups of 1-100, 101-200, or over 200, respectively. The user must choose a guest number category to see an event’s price.

• A ButtonGroup is appropriate because the options are mutually exclusive; you would not want a user to be able to select two or three categories

(39)

An Application that uses a ButtonGroup

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JButtonGroupDemo extends Jframe implements ItemListener

{

• Declare three variables to hold the event prices for the three categories, and three JCheckBoxes from which the user can select the party size.

• Make the first JCheckBox the default option by using true in its constructor call.

39

(40)

int guestPremium1 = 1300;

int guestPremium2 = 2400;

int guestPremium3 = 6000;

JCheckBox guestBox1 =new JCheckBox(“1-100 guests $” + guestPremium1, true);

JCheckBox guestBox2 =new JCheckBox(“101-200 guests $” + guestPremium2, false);

JCheckBox guestBox3 =new JCheckBox(“1-100 guest $” + guestPremium3, false);

(41)

• Create some JLabels that explain the application’s purpose, and a JTextField in which to display the price for the selected guest option:

JLabel eventHandlersLabel = new JLabel("Event Handlers Incorporated");

JLabel ePrice = new JLabel("The price for your event is");

JTextField totPrice = new JTextField(10);

JLabel optionExplainLabel = new JLabel("Base price for an event is

$" + basePrice + ".");

JLabel eventExplainLabel= new JLabel("Check the number of guests at your event.");

41

(42)

• Begin to create the JButtonGroupDemo constructor method. Set the title, the close operation and declare aJPanel to hold components:

public JButtonGroupDemo() {

supper(“Event Price Estimator”)

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();

pane.add(eventHandlersLabel);

pane.add(eventExplainLabel);

pane.add(guestBox1);

pane.add(guestBox2);

pane.add(guestBox3);

ButtonGroup guestGroup = new ButtonGroup();

42

(43)

guestGroup.add(guestBox1);

guestGroup.add(guestBox2);

guestGroup.add(guestBox3);

pane.add(ePrice);

pane.add(totPrice);

43

(44)

• Set the text of the totPrice field so that when the application begins it holds the first guest premium amount by default. Use the addItemListener() method to register the class as a listener to events generated by each of the check boxes. set the content pane for the application and include a closing curly brace for the constructor method:

totPrice.setText(“$” + guestPremium1) guestBox1.addItemListener(this);

guestBox2.addItemListener(this);

guestBox3.addItemListener(this);

setontentPane(pane);

(45)

• Write a main() method that declares a JButtonGroupDemo object, set it size, and makes it visible:

public static void main(String[] args) {

JFrame aFrame = new JButtonGroupDemo();

aFrame.setSize(300,250);

aFrame.setVisible(true);

}

45

(46)

• Write an ItemStateChanged() method.

• Use a nested if statement with the isSelected() method to determine which of the three JCheckBoxes in the ButtonGroup is selected and set the text of the totPrice field with the appropriate price:

public void itemStateChanged(ItemEvent event) {

if(guestBox1.isSelected())

totPrice.setText(“$” + guestPremium1);

else if (guestBox2.isSelected())

totPrice.setText(“$” + guestPremium2);

(47)

Using the JComBoBox Class

• A JComboBox is a component that combines a display area showing an option with a drop- down list containing additional options.

• You can build a JComboBox by using a constructor with no arguments and then adding items (for e.g. strings) to the list with the addItem() method.

47

(48)

• The following statement create a JComboBox named majorChoice containing three options from which a user can choose:

JConboBox majorChoice = new JComboBox ();

majorChoice.addItem(“English”);

majorChoice.addItem(“Maths”);

majorChoice.addItem(“Sociology”);

• Alternately

• String[] majorArray = {“English”,”Maths”,”Sociology”};

• JComboBox majorChoice new JComboBox(majorArray);

(49)

An Application Containing Many Swing Components

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

public class JEventPriceEstimator extends JFrame implements ItemListener

{

• Declare a number of variables to use in the program:

int cocktailPrice = 15;

int chickenPrice = 0; basePrice = 8, fishPrice = 5;

49

(50)

int[] favorPrice = {0, 1, 2, 4, 6};

int favPrice = 0;

int basePrice = 20, totalPrice = basePrice;

• Declare JCheckBoxes for the optional cocktail service and the three entrees:

JCheckBox cocktailBox = new JCheckBox(“Cocktails $” + cocktailPrice, false);

JCheckBox chickenBox = new JCheckBox(“Chicken $” + chickenPrice, true);

JCheckBox beefBox = new JCheckBox(“Beef $” + beefPrice, false);

JCheckBox fishBox = new JCheckBox(“Fish $” + fishPrice, false);

50

(51)

• Declare a JLabel describing the party favor option, then declare an array of String that holds the favor names:

Jlabel favorLabel = new Jlabel(“Party favors: Make a selection”);

String[] favorNames = {“None $” + favorPrice[0], “Hat $” +

favorPrice[1], “Streamers $” + favorPrice[2], “Noise Maker $” + favorPrice[3], “Helium Balloons $” + favorPrice[4]};

JComboBox favorBox = new JComboBox(favorNames);

51

(52)

• Add the remaining string components the application requires:

JLabel eventHandlersLabel = new JLabel(“Event Handlers Incorporated”);

JLabel ePrice = new JLabel(“Per person event price estimate”);

JtextField totPrice = new JTextField(10);

JtextField message = new JTextField(30);

JLabel optionExplainLabel = new JLabel("Base price for dinner with chicken entree is $" + basePrice + ".");

JLabel optionExplainLabel2 = new JLabel(“Optionally, you can choose to serve cocktails");

JLabel optionExplainLabel3 = new JLabel("and change the entree to beef or fish");

52

(53)

• Create a constructor for the JEventPriceEstmator class:

public JEventPriceEstimator() {

super(“Event Price Estimator”);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel pane = new JPanel();

ButtonGroup dinnerGroup = new ButtonGroup();

dinnerGroup.add(chickenBox);

dinnerGroup.add(beefBox);

dinnerGroup.add(fishBox);

Pane.add(cocktailBox);

pane.add(chickenBox);

pane.add(chickenBox);

53

(54)

pane.add(beefBox);

pane.add(fishBox);

pane.add(favorLabel);

pane.add(favorBox);

pane.add(eventHandlersLabel);

pane.add(optionExplainLabel);

pane.add(optionExplainLabel2);

pane.add(optionExplainLabel3);

pane.add(ePrice);

pane.add(totPrice);

pane.add(message);

totPrice.setText(“$” + totalPrice);

54

(55)

cocktailBox.addItemListener(this);

chickenBox.addItemListener(this);

beefBox.addItemListener(this);

fishBox.addItemListener(this);

favorBox.addItemListener(this);

setContentPane(pane);

}

55

(56)

• The main() method for the class declares a Jframe object and sets its size and visibility:

public static void main(string[] args) {

JFrame aFrame = new JEventPriceEstimator();

aFrame.setSize(400, 250);

aFrame.setVisible(true);

}

public void itemStateChanged(ItemEvent event) {

object source = event.getSource();

(57)

int select = event.getStateChange();

if (source == cocktailBox)

if(select == ItemEvent.SELECTED)

message.setText(“Action: Cocktails selected”);

else

message.setText(“Action: Cocktails deselected”);

else if (source == favorBox) {

int favNum = favorBox.getSelectedIndex();

favPrice = favorPrice[favNum];

message.setText(“Action: Favor selection changed: $ ” + favPrice + “ added”

}

57

(58)

else

message.setText(“Action: Meal change made”);

• Compute the event’s per-person total price by adding the selected favor price to the base price:

totalPrice = basePrice + favPrice;

if(beefBox.isSelected()) totalPrice += beefPrice;

else if(fishBox.isSelected()) totalPrice += fishPrice;

if(cocktailBox.isSelected()) totalPrice += cocktailPrice;

totPrice.setText(“$” + totalPrice);

}

(59)

• Add closing curly brace and save it.

59

References

Related documents