Beruflich Dokumente
Kultur Dokumente
GUI development
Swing is
A big API
Built on AWT (another big API)
Used for GUI's
AWT
Swing
Container
Frame
JFrame
JApplet
JComponent
Window
Panel
Dialog
JWindow
JDialog
JLabel
JPanel
JTable
JTree
Color,(animmutableclass)
Point,
Dimension,
Font
JOptionPane Examples
JComboBox
Progress Bar
Displays progress of operation
Can be used like a gauge
Usage:
Initialize
JProgressBar progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setMaximum(numberSubOperations);
Go
progressBar.setValue(progressBar.getMinimum());
for (int i = 0; i < numberSubOperations; i++) {
progressBar.setValue(i);
performSubOperation(i);
}
When?
Use a progress bar whenever users are
blocked from interacting with the
application for more than 6 seconds.
Use
Users cannot interact with a progress bar.
Update the progress bar to show the proportion
completed at least every 4 seconds.
If you overestimate how much is already done,
the progress bar can remain at 99 percent until the
task is complete.
If you underestimate how much is already done,
fill the remaining portion of the progress bar when
the operation completes.
The percentage done should never decrease.
AWT
Swing
Container
Frame
JFrame
JApplet
JComponent
Window
Panel
Dialog
JWindow
JDialog
JLabel
JPanel
JTable
JTree
Progress Bar
Displays progress of operation
Can be used like a gauge
Usage:
Initialize
JProgressBar progressBar = new JProgressBar();
progressBar.setMinimum(0);
progressBar.setMaximum(numberSubOperations);
Go
progressBar.setValue(progressBar.getMinimum());
for (int i = 0; i < numberSubOperations; i++) {
progressBar.setValue(i);
performSubOperation(i);
}
JProgressBar Methods
javax.swing.JComponent
javax.swing.JProgressBar
+JProgressBar()
+JProgressBar(orient: int)
Creates a progress bar with min 0 and max 100 and a specified orientation.
+getMaximum(): int
+getMinimum(): int
+getOrientation(): int
+getPercentComplete():double
Returns the percent complete for the progress bar. 0 <= a value <= 1.0.
+getValus(): int
+getString(): String
+isStringPainted(): Boolean
+setStringPainted(b: boolean): void Sets the value of the stringPainted property, which determines whether the
progress bar should render a progress percentage string. (default: false)
CopyFile
Run
Basic Controls
Menu related classes
The Components
A subclass of the java.awt.Component class
is called a Component
A Component has a size, color, etc.
A Component can normally be painted.
When a component is painted it is visible
on the screen.
Component Subclasses
basic components
JComboBox a dropdown list with optional editable
text field. The user can key in a value or select a value
fromdropdownlist.
Jlist
list.
acomponentusertoeditanddisplaydatainatwodimensional
grid.
JTextArea,JTextPane,JEditorPane
definemultilineareasfordisplaying,entering,andeditingtext.
Swing components
Container
Componentthatcancontainothercomponentsandcontainers.
Component
Container
JCom ponent
has
Intermediate components
Used to organize and position other
components.
JPanelcontainerofcomponents.
JScrollPanepanelwithscrollbars.
JSplitPanedividestwocomponentsgraphically.
JTabbedPane lets the user switch between a group of
componentsbyclickingonalabeledtab;
JToolBarusedfordisplayingasetofcommonlyusedcontrols.
Example of component
organization
ThefollowingcreatesaJPanelandaddstwobuttons,labeledon
andoff.
JPanel p = new JPanel();
p.add(new JButton("on"));
p.add(new JButton("off"));
Top-level container
Itsnotcontainedinanyothercontainer.
provide screen area where other
componentscandisplaythemselves.
JApplet, JDialog, JFrame, and JWindow are
commonlyusedastoplevelcontainers.
JFrame
Its a window with title, border, (optional)
menubaranduserspecifiedcomponents.
Itcanbemoved,resized,iconified.
ItisnotasubclassofJComponent.
Delegates responsibility of managing user
specifiedcomponentstoa contentpane,an
instanceofJPanel.
Jframe
Jframe
JFrame
ToaddacomponenttoaJFrame,addittothecontentpane:
content pane
Container
Component
Swing vs AWT
Swing has lightweight
components
Light weight
components have no
peers
Look and feel
variations available
Swing is SLOW
AWT is heavyweight
heavyweight comps
require peers.
Always looks like the
platform it runs on.
AWT is FAST
Simple Input
public class In {
public static String getString(Object o) {
return JOptionPane.showInputDialog(o);
}
How do we get an int?
Getting an Int
public static int getInt(Object o) {
return Integer.parseInt(
getString(o));
}
JList
a component that allows a user to select one or
more elements from a list
String[] data = {"one", "two", ...};
JList list = new JList(data);
JList
requires a ListSelectionListener that implements
public void valueChanged(ListSelectionEvent e) {
if (e.getValueIsAdjusting() == false) {
//selected: list.getSelectedValue()
}
}
list.setSelectionMode(ListSelectionModel.SINGLE
_SELECTION);
dynamic jlist
create the list and pass in the ListModel as input
add or remove elements in the ListModel
the GUI will update the list dynamically
DefaultListModel listModel = new
DefaultListModel();
JList list = new JList(listModel);
listModel.addElement(object);
listModel.removeElement(i);
Scroll Panes
sometimes the list will be too long to display in
the GUI
Solution: display the list inside a JScrollPane
jsp
JScrollPane sp = new
JScrollPane(list);
list.setVisibleRowCount(5);
add(sp);
Atomic IO
Atomic actions happen all at once.
Event driven call-backs can complicate
code.
EmployeeRecord = getEmployeeRecord();
How is getEmployeeRecord implemented?
JDialog
Usedtocreatecustomdialogwindows.
AJdialog
atoplevelwindow.
hasanowner,generallyaframe.
It delegates component management to a
contentpane,towhichcomponentsareadded.
Its displayed by invoking its setVisible
method with an argument of true, and is
hidden by invoking its setVisible method
withanargumentoffalse
JDialog
Atypicalconstructorisspecifiedasfollows:
Implementing getXXX
get data
from a file
from the web
from the user
from
JColorChooser dialogs
JColorChooserpresentsapaneofcontrolsthatallowausertoselectand
manipulateacolor.
Error Control
int I = getInt(enter an int [1..10],1,10);
The getInt function protects the range on
the int. If the value is not correct, we
prompt the user again.
The RHS waits for the assignment to
complete
JFileChooser
Swing provides a file chooser implemented in 100% pure Java
FileChooser
JFileChooser directory = new JFileChooser();
directory.setCurrentDirectory(new File(.));
directory.showOpenDialog(this); //open dialog
File file = directory.getSelectedFile();
JFileChooser.getSelectedFiles
The JFileChooser abstracts the file view from the chooser using the
javax.swing.filechooser.JFileView abstract class
You can write your own file view by subclassing JFileView and passing it to the
JFileChooser
f.setFileView (new ImageFileView());
Get a Directory
A Directory Chooser
public static File getReadDirFile(String
prompt) {
String dir =
DirectoryChooser.getDirectory(prompt);
if (dir==null) return null;
File f = new File(dir);
return f;
}
Layouts
FlowLayout
GridLayout
BorderLayout
BoxLayout
GridBagLayout.
What are these layouts for?
Gui.layouts
DialogLayout
ParagraphLayout
Simple ParagraphLayout
ParagraphLayout
PreferredSizeGridLayout
How do I use
PreferredSizeGridLayout?
PreferredSize
Call:
Dimension getPreferredSize(){}
To get the preferred size of any component.
VerticalFlowLayout
GridLayout
FlowLayout
BoxLayout
Vertical Flow
JTree
JTree Example
JTree
A tree is a set of hierarchical nodes.
The top of this hierarchy is called root.
An element that does not have children is
called leaf.
JTree nodes are managed by a TreeModel.
TreeCellRenderer converts an object to its
visual representation in the tree.
TreeModel
Hierarchical data
Parents
Children
Siblings
Ancestors
Descendents
TreeModel
Object getRoot()
Object getChild(Object parent, int index)
int getChildCount(Object parent)
boolean isLeaf(Object node)
void valueForPathChanged(TreePath path, Object newVal)
int getIndexOfChild(Object parent, Object child)
void addTreeModelListener(TreeModelListener l)
void removeTreeModelListener(TreeModelListener l)
JTree constructors
JTree()
JTree(Object[] value)
JTree(Vector value)
JTree(Hashtable value)
JTree(TreeNode root)
JTree(TreeNode root, boolean
asksAllowsChildren)
JTree(TreeModel newModel)
TreeNodes
Default tree model uses objects of TreeNode to represent the nodes in the
tree.
A default implementation of it is DefaultMutableTreeNode.
TreeNode methods
DefaultMutableTreeNode constructors
DefaultMutableTreeNode()
DefaultMutableTreeNode(Object userObject)
DefaultMutableTreeNode(Object userObject, boolean allowsChildren)
JTree example
import javax.swing.* ;
import javax.swing.tree.* ;
import java.awt.event.* ;
import java.awt.* ;
import java.util.* ;
public class TreeNodeExample extends JPanel {
public TreeNodeExample() {
DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Categories") ;
DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode("Metals") ;
parentNode.add(new DefaultMutableTreeNode("Gold",false)) ;
parentNode.add(new DefaultMutableTreeNode("Silver",false)) ;
parentNode.add(new DefaultMutableTreeNode("Bronze",false)) ;
parentNode.add(new DefaultMutableTreeNode("Copper",false)) ;
parentNode.add(new DefaultMutableTreeNode("Iron",false)) ;
parentNode.add(new DefaultMutableTreeNode("Platinium",false)) ;
parentNode.add(new DefaultMutableTreeNode("Titanium",false)) ;
rootNode.add(parentNode) ;
parentNode = new DefaultMutableTreeNode("Companies") ;
parentNode.add(new DefaultMutableTreeNode("Paradigm Research",false)) ;
parentNode.add(new DefaultMutableTreeNode("JavaSoft",false)) ;
parentNode.add(new DefaultMutableTreeNode("Wiley Press",false)) ;
rootNode.add(parentNode) ;
setLayout(new BorderLayout());
add(new JScrollPane(new JTree(rootNode)),"Center") ;
}
public Dimension getPreferredSize()
{ return new Dimension(200,120) ; }
public static void main(String[]args) {
JFrame frame = new JFrame("Tree Node Example") ;
TreeNodeExample panel = new TreeNodeExample() ;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
frame.getContentPane().add(panel,"Center") ;
frame.setSize(panel.getPreferredSize()) ;
frame.setVisible(true) ;
}
}
TreeModel Listener
TreeModelListener methods
void treeNodesChanged(TreeModelEvent e)
void treeNodesInserted(TreeModelEvent e)
void treeNodesRemoved(TreeModelEvent e)
void treeStructureChanged(TreeModelEvent e)
TreeModelEvent methods
TreePath getTreePath()
Object[] getPath()
Object[] getChildren()
int[] getChildIndices()
Custom TreeModel
Implementation
Implement interface TreeModel
import java.io.* ;
import java.util.* ;
class FileHolder {
File myFile ;
Vector children ;
public FileHolder(File f)
{ myFile = f ; }
public File getFile()
{ return myFile ; }
public Vector getChildren() {
if (myFile.isDirectory() && (children==null)) {
int max=0;
String list[] ;
File curFile ;
FileHolder curHolder ;
children = new Vector() ;
list = myFile.list() ;
if (list!=null)
max = list.length ;
for (int i=0;i<max;++i) {
curFile = new File(myFile,list[i]) ;
curHolder = new FileHolder(curFile) ;
children.addElement(curHolder) ;
}
}
return children ;
}
public String toString()
{ return myFile.getName() ; }
}
import javax.swing.* ;
import javax.swing.tree.* ;
import javax.swing.event.* ;
import java.io.* ;
import java.util.* ;
class FileSystemTreeModel implements TreeModel {
protected FileHolder root ;
protected Vector listeners ;
public FileSystemTreeModel(File r)
{ root = new FileHolder(r) ;
listeners = new Vector() ; }
public Object getRoot()
{ return root ; }
public Object getChild(Object parent, int index)
{ Object retVal=null ;
Vector children ;
if (parent instanceof FileHolder) {
children = ((FileHolder)parent).getChildren() ;
if (children!=null)
if (index<children.size())
retVal=children.elementAt(index) ;
}
return retVal ; }
public int getChildCount(Object parent)
{ int retVal = 0 ;
Vector children ;
if (parent instanceof FileHolder) {
children = ((FileHolder)parent).getChildren() ;
if (children!=null)
retVal = children.size() ;
}
return retVal ; }
Jtree
DefaultTreeModel
Interface TreeModel
Declares methods for representing tree structure
Class DefaultTreeModel
Default TreeModel implementation
TreeNode
MutableTreeNode
DefaultMutableTreeNode
JTree Architecture
interface
TreeModel
getRoot() : Object
getChildCount(in parent : Object) : int
getChild(in parent : Object, in index : int) : Object
getIndexOfChild(in parent : Object, in child : Object) : int
isLeaf(in node : Object) : boolean
valueForPathChanged(in Parameter1)
model
JTree
uiDelegate
TreeUI
interface
RowMapper
BasicTreeUI
1
interface
TreeNode
DefaultTreeModel
root
treePathMapping
AbstractLayoutCache
1
*
interface
MutableTreeNode
0..*
FixedHeightLayoutCache
DefaultMutableTreeNode
children
parent
VariableHeightLayoutCache
TreePaths (1)
lastPathComponent
parentPath
TreePaths (2)
A child TreePath prevents all of its ancestors from
being gcd
Used throughout JTree as a unique address for a tree
node
Allows equal() node objects to be used in the
same tree
Some duplicate functionality with the data model
trace node parentage
indent level
higher speed, more memory
FixedHeightLayoutCache
Caches only expanded visible nodes
Only enabled if JTree largeModel = true and
rows are explicitly set to a fixed height
previously expanded
fixed
height
variable
height
import java.io.* ;
import java.util.* ;
class FileHolder {
File myFile ;
Vector children ;
public FileHolder(File f)
{ myFile = f ; }
public File getFile()
{ return myFile ; }
public Vector getChildren() {
if (myFile.isDirectory() && (children==null)) {
int max=0;
String list[] ;
File curFile ;
FileHolder curHolder ;
children = new Vector() ;
list = myFile.list() ;
if (list!=null)
max = list.length ;
for (int i=0;i<max;++i) {
curFile = new File(myFile,list[i]) ;
curHolder = new FileHolder(curFile) ;
children.addElement(curHolder) ;
}
}
return children ;
}
public String toString()
{ return myFile.getName() ; }
}
import javax.swing.* ;
import javax.swing.tree.* ;
import javax.swing.event.* ;
import java.io.* ;
import java.util.* ;
class FileSystemTreeModel implements TreeModel {
protected FileHolder root ;
protected Vector listeners ;
public FileSystemTreeModel(File r)
{ root = new FileHolder(r) ;
listeners = new Vector() ; }
public Object getRoot()
{ return root ; }
public Object getChild(Object parent, int index)
{ Object retVal=null ;
Vector children ;
if (parent instanceof FileHolder) {
children = ((FileHolder)parent).getChildren() ;
if (children!=null)
if (index<children.size())
retVal=children.elementAt(index) ;
}
return retVal ; }
public int getChildCount(Object parent)
{ int retVal = 0 ;
Vector children ;
if (parent instanceof FileHolder) {
children = ((FileHolder)parent).getChildren() ;
if (children!=null)
retVal = children.size() ;
}
return retVal ; }
Class: javax.swing.JTable
Swing Component
displays data in table
edit the data
JTable properties
Column is the basic unit of the Table.
Row collection of columns
Cell the location of data.
Architecture
MVC (Model-View-Controller)
Model:data of the components.
View:visual representation.
Controller:describe how the component
interacts with user.
MVC
ModelClass
ViewClass
DataAccessor
Methods
DisplayMethods
ControllerClass
EventHandling
Methods
MVC
MVC paradigm
Model
Data storage, no presentation elements
View
No data storage, presentation elements
Constructors:
String[] columnNames =
{
First Name,
Last Name,
Sport,
# of Years,
Vegetarian
};
JTable table = new JTable(data,
columnNames);
Interfaces
TableColumnModel manages column
selection and spacing
TableModel provides data.
Events
TableColumnEvent caused by column
model changed.
TableModelEvent caused by TableModel
changed
Change Width
TableColumn column;
for (int i = 0; i < 5; i++)
{
column =
table.getColumnModel().getColumn(i);
if (i == 2)
column.setPreferredWidth(100);
else
column.setPreferredWidth(50);
Build Model
TableModel tm = new AbstractTableModel()
{
public void getColumnCount()
{
return columnNames.length;
}
public void getRowCount()
{
return data.length;
}
public Object getValueAt(int row, int col)
{
return data[row][col];
}
public Class getColumnClass(int col)
{
return getValueAt(0, col).getClass();
Split pane
Allows user-controlled resizing of two
components
Can move divider programmatically with
setDividierLocation
int parameter
absolute position
float parameter
percentage
Tabbed Pane
Tabbed panel control
Similar to using CardLayout with buttons
for selecting cards
Use addTab to add components/panels
The JDesktopPane
Parent JLayeredPane.
Can hold multiple overlapping internal
frames.
Internal frames may be dragged, resized,
iconified.
events handled by DesktopManager.
JDesktopPane Pro
more window behavior control over than
JFrames.
Can control minimization,
Can control window look and feel.
Appearance same on all platforms, easily
configurable.
Cons
Requires more management.
Cant just add components without saying
where.
Minimization prefs.
JDesktopPane and
JInternalFrame
Multiple-document interface
A main window (called the parent window)
contains other windows (called child windows)
Manages several open documents that are being
processed in parallel
Implemented by Swings JDesktopPane and
JInternalFrame
Using JInternalFrame
Main constructor
public JInternalFrame(String title,
boolean resizable,
boolean closeable,
boolean maximizable,
boolean iconifiable)
moveToFront
moveToBack
setSize (required!)
setLocation (required!)
Internal Frames:
Example Output
Internal Frames
Minimize
Maximize
Close
Outline
DeskTopTest.java
(2 of 3)
Outline
DeskTopTest.java
(3 of 3)