Download GUI Application: Understanding Swing Components and Event Handling and more Schemes and Mind Maps Java Programming in PDF only on Docsity!
LECTURE 11: GUI APPLICATION
o GUI
o GUI Components
o Event Handler
PLAN
o Built from GUI components.
- Sometimes called controls or widgets—short for window gadgets.
o User interacts via the mouse, the keyboard or another form of input,
such as voice recognition.
o IDEs
- Provide GUI design tools to specify a component’s exact size and
location in a visual manner by using the mouse.
- Generates the GUI code for you.
- Greatly simplifies creating GUIs, but each IDE has different
capabilities and generates different code.
Introduction (cont.)
GUI Example
o Most Swing components are not tied to actual GUI components of
the underlying platform.
- Known as lightweight components.
o AWT components are tied to the local platform and are called
heavyweight components, because they rely on the local
platform’s windowing system to determine their functionality and
their look-and-feel.
o Several Swing components are heavyweight components.
Overview of Swing Components
Using JOptionPane for Output
import javax.swing.*;
...
JOptionPane.showMessageDialog( null, “I Love Java” );
JOptionPane for Input
import javax.swing.*;
...
String inputstr =
JOptionPane.showInputDialog( null, “What is your name?” );
JOptionPane static constants
o To create a customized frame window, we define a subclass of the
JFrame class.
o The JFrame class contains rudimentary functionalities to support
features found in any frame window.
Subclassing JFrame
Creating a Plain JFrame
import javax.swing.*;
class DefaultJFrame {
public static void main( String[] args ) { JFrame defaultJFrame; defaultJFrame = new JFrame(); defaultJFrame.setVisible(true); }
}
o The content pane is where we put GUI objects such as buttons,
labels, scroll bars, and others.
o We access the content pane by calling the frame’s
getContentPane method.
The Content Pane of a Frame
This gray area is the content pane of this frame.
o Here's how we can change the background color of a content
pane to blue:
Changing the Background Color
Container contentPane = getContentPane(); contentPane.setBackground(Color.BLUE);
o A JButton object a GUI component that represents a pushbutton.
o Here's an example of how we place a button with FlowLayout.
Placing a Button
contentPane.setLayout( new FlowLayout()); okButton = new JButton("OK"); cancelButton = new JButton("CANCEL"); contentPane.add(okButton); contentPane.add(cancelButton);
o Many IDEs provide GUI design tools in which you can specify the
exact size and location of a component
o IDE generates the GUI code for you
o Greatly simplifies GUI creation
o To ensure that this book’s examples can be used with any IDE, we
did not use an IDE to create the GUI code
o We use Java’s layout managers in our GUI examples
IDE Help for GUI Desgin