Title: Some Quick Notes on Swing
1Some Quick Notes on Swing
- Swing is the package(s) that
- give you an interface to the window system in the
operating system (Windows or X, if you're using
Linux) - gives you methods for creating graphical objects
like rectangles, text areas - gives you controls that accept user input
- text boxes that allow editing
- push buttons and radio buttons, sliders
- The general model for Swing is to create a JFrame
object which has two functions - it is a visible window on the monitor
- it is a Java object that you can control
- With a JFrame you can put components (graphical
objects, controls) in the frame, according to
some layout - You then listen for "events" that the user
triggers in the frame, and take appropriate
action - typing in a text area
- pushing a button or clicking a control
2An Easy Subset of Swing
- For now we can use a utility class that is very
easy to use, and provides some basic
functionality - an alert box that allows us to do output
- an input dialog box that allows user input
- an option dialog box that allows menu choices
- Class is JOptionPane (also see section 1.7 in the
book)
3The Three Calls
// Simple output JOptionPane.showMessageDialog(nu
ll, "I want you to see this") String userInput
JOptionPane.showInputdialog("Give me some
input") String menuOptions "Forward",
"Backward", "Stop" int choice
JOptionPane.showOptionDialog( null,
"User prompt", "Window name" JOptionPane.YES_
NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE,
null, menuOptions, menuOptions0) //
choice will be 0, 1, or 2 when this call
returns
Plusses Very easy, and don't have to keep
track of your own windows and frames and
layouts Minuses Every interaction is in its
own separate window. No text formatting,
which limits how interesting the text output
can be
4Our Design Problem Now
- To build a class that incorporates these Swing
features to implement the interface - If we can do that, our course user interface will
work exactly the same whether it is interacting
with the user via graphics or via the console
public interface IOUtilitiesInterface
String getString(String prompt) int
getMenuOption(String header, String options)
int getInt(String prompt, int low, int high)
int getInt(String prompt) boolean
getYesNo(String prompt) void print(String
text)
5Displaying Formatted Text in an External Window
JFrame frame new JFrame("Class
List") JTextArea textArea new JTextArea ()
textArea.setEditable(false) frame.getContentPan
e().add(textArea) frame.setBounds(100, 100, 500,
500) frame.setVisible(true) textArea.append("Hel
lo world\n\tOne\n\tTwo\n\tThree")
Now the challenge question how to incorporate
this functionality into the InputUtilities, so
that the Swing interface has the ability to print
the class list nicely, but the application still
works even with the console utility.