AWT and Swing - schmiedecke.info

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 9 months ago)

92 views










 



oopjs4b / kwhbkd4r
(c) schmiedecke 05inf1-11 GUIs2
GUI Elements: WIMP

GUIsare
windows
,
possiblywith subwindowsor
panels
,
with"
widgets
" placedtherein

WidgetmeansWindowGadget:
handle forwindowinteraction

inventedin the60's, in usesincethe80's

Basic concept:
WIMP
W
I
M
P
(Multiple) Windows
Icons
Menus
Pointing Device
oopjs4b / kwhbkd4r
(c) schmiedecke 05inf1-11 GUIs3
Developmentof GUIs
•First implementation1973: Alto-Computer von Xerox:
3-button mouse.
Bit-mappeddisplay.
Theuseof graphicalwindows.
Ethernet network
•1981 Xerox Star
•1983 Apple Lisa
•1984 Mac X
•1985 C64, Amiga 1000 Workbench, firstMS
Windows-Version...
http://toastytech.com/guis/guitimeline.html
(c) schmiedecke 05inf1-11 GUIs4
Java AWT
(c) schmiedecke 05inf1-11 GUIs5
Java-Swing
(c) schmiedecke 05inf1-11 GUIs6
AWT and Swing
....
JTextfieldTexfield
JButtonButton
JLabelLabel
JFrameFrame
packagejavax.swingpackagejava.awt
SwingAWT
JBit??
As Swing isbasedon awt, bothpackageshave
to beimportedin mostcases.
(c) schmiedecke 05inf1-11 GUIs7
NeverWorkwithoutAPI Specification!
•AWT and Swing are large libraries
•Youcan'tknowall theclassesin detail.
•Ifyouhaven'tdoneso, bookmarkor
download theAPI specificationnow!
http://java.sun.com/j2se/1.5.0/docs/api/
(c) schmiedecke 05inf1-11 GUIs8
AWT Components
(c) schmiedecke 05inf1-11 GUIs9
Swing Components
(Selection)
Container
Window
JComponent
JPanel
JLabel
AbstractButton
JButton
JCheckBox
JRadioButton
JComboBox
JTextComponent
JTextField
JTextArea
JEditorPane
JSlider
JProgressBar
JTable
JTree
JFrame
JDialog
"Widget" =
Window
Gadget
(c) schmiedecke 05inf1-11 GUIs10
Start witha Main Window:
Applicationwindow:
JFrame
Basic programstructureforGUIs:
1.ExtendJFrame.
2.Do thebasicsetupin theconstructor,
includinga callof init().
3.Useinit() to setup thecomponents.
4.Instantiateyourwindowin main().
(c) schmiedecke 05inf1-11 GUIs11
publicclassMainWindow
extendsJFrame
{
publicMainWindow()
{
setTitle("Fenster im Aufbau");
init();
// still empty
setSize(400,400);
setVisible(true);
}
private voidinit()
{}
publicstaticvoidmain
(String[] args){
newMainWindow();
}
}
(c) schmiedecke 05inf1-11 GUIs12
AddWidgets

DeclareWidgets.

ChooseLayout (e.g.FlowLayout)

CallContainer methodadd()
Up to Java 1.4: do notapplyadd()
directlyto JFrame, butto ContentPane
For complicatedlayoutsonly:
callpack() to finalizepositioning.
private voidinit() {
JButton taste = newJButton("clear");
JTextFieldtext = newJTextField(" 0.0");
setLayout(newFlowLayout());
Container fenster= this;
// Java 1.4: this.getContentPane();
fenster.add(taste);
fenster.add(text);
}
(c) schmiedecke 05inf1-11 GUIs13
Set up componentsin init()
private voidinit() {
JLabellogin= newJLabel
("Bitte melden Sie sich an!");
JLabeluser= newJLabel("username:");
JTextFielduserfield= newJTextField(" ");
JLabelpw= newJLabel("password:");
JTextFieldpwfield= newJTextField("", 15);
JButtonok= newJButton("ok");
Container window= this; // Java 1.4: .getContentPane
();
window.setLayout(newFlowLayout());
window.add(login);
window.add(user);
window.add(userfield);
window.add(pw);
window.add(pwfield);
window.add(ok);
}
(c) schmiedecke 05inf1-11 GUIs14
Layout organized
as FlowLayout
(c) schmiedecke 05inf1-11 GUIs15
ModifyComponentAppearance
Componentshaveproperties, such as
–size
–font
–colors
–text
–image
Propertiescanbeaccessedthroughget/set
methods.
WeusedsetImageIconon a JLabelin the
alarmclockanimation.
(c) schmiedecke 05inf1-11 GUIs16
JLabellogin= newJLabel
("Bitte melden Sie sich an!");
login.setFont(newFont("Helvetica",Font.BOLD,16));
login.setForeground(Color.blue);
Lettheloginmessagebebiggerand blue
(c) schmiedecke 05inf1-11 GUIs17
Passive Interaction:
Text Components
•A text componentcanbemadeeditable:
setEditable(true)
•User inputcanbereadfrompropertytext:
getText()
JTextFielduserfield= newJTextfield(" ");
JTextFieldpwfield= newJTextfield(14);
userfield.setEditable(true); // default
pwfield.setEditable(true); // default
String user= userfield.getText();
String passwort= pwfield.getText();
(c) schmiedecke 05inf1-11 GUIs18

A CheckBoxcanbecheckedinteractively

A RadioButtoncanbesetinteractively(oftenusedin
RadioButtonGroup–onlyonebuttonsetat a time )

Read settingusingisSelected()
Passive Interaction:
CheckBoxand RadioButton
JCheckBoxcheck = newJCheckBox("akzeptiere");
JRadioButtonyes= newJRadioButton("ja");
JRadioButtonno = newJRadioButton("nein");
ButtonGroupyesno= newButtonGroup();
yesno.add(ja);
yesno.add(nein);
window.add(ja);
window.add(nein);
window.add(check);
(c) schmiedecke 05inf1-11 GUIs19
A ComboBoxisa selectionlist which
popsup on interaction
Bothpoppingup and selectionare dealt
withinsidethecomponent, setting
properties
Readtheselectionpropertiesusing
getSelectedIndexor
getSelectedItem
Passive Interaction:
ComboBox
JComboBoxcombo1 = newJComboBox();
combo1.addItem("männlich");
combo1.addItem("weiblich");
String[] addr= {"Herr", "Frau", "Firma"};
JComboBoxcombo2 = newJComboBox(addr);
window.add(combo1);
window.add(combo2);
(c) schmiedecke 05inf1-11 GUIs20

Dialogs are usually
modal windows
requestinguserinput.

Theshowupfunction"show..."
yieldstheinput
as result, if
applicable.

JDialog
isa universal dialogwindow:
–configureJDialogusingconstructorparameters
–orextendJDialog

Swing has manyusefulready-madedialogs:
JOptionPane
: dialogsforyes/no, choiceorinput
–JFileChooser
: dialogforfilesystemaccess
–JColorChooser
: colorspecificationdialog
–...
Ready-Made Interaction Windows:
Dialogs
(c) schmiedecke 05inf1-11 GUIs21
JOptionPane.showMessageDialog
(null, //
minddeadlock!
"Controller reagiert nicht",
"Alarm",
JOptionPane.ERROR_MESSAGE);
JOptionPane.showMessageDialog
(null, //
minddeadlock!
"nicht zertifiziert",
"Warnung",
JOptionPane.WARNING_MESSAGE);
JOptionPane.showConfirmDialog
(null, //
minddeadlock!
"Löschen?",
"Bestätigung",
JOptionPane.YES_NO_OPTION);
(c) schmiedecke 05inf1-11 GUIs22
String eingabe=
JOptionPane.showInputDialog
("Bitte Wert eingeben:");
System.out.println
("eingegeben: "+ eingabe);
Object[] werte =
{ "alpha", "beta", "gamma" };
Objectauswahl=
JOptionPane.showInputDialog
(null,
"Bitte wählen Sie",
"Auswahl",
JOptionPane
.INFORMATION_MESSAGE,
null, //
minddeadlock!
werte, werte[1]);
System.out.println
("gewählt: "+auswahl);
(c) schmiedecke 05inf1-11 GUIs23
JFileChooser
JFileChooserchooser= newJFileChooser();
JFilefile= chooser.showOpenDialog(
window
);
(c) schmiedecke 05inf1-11 GUIs24
JColorChooser
JColorChoosercolors= newJColorChooser();
Color color= colors.showDialog
(window, "Farbwahl", Color.blue);
(c) schmiedecke 05inf1-11 GUIs25
Menus
•JMenuBarcontainsJMenu's
•JMenucontainsJMenuItem'sorJMenu's
•JMenuItem'smaybe
–Strings
–Icons
–Icons + String
–CheckBoxesorRadioButtons
•AddJMenuBarto themainwindowusing
setJMenuBar()

Menus, too, allowevent-freeinteractionusing
getSelectedItem() orgetSelectedIndex(),
butdoingso contradictscommonpractice.
(c) schmiedecke 05inf1-11 GUIs26
Menu setup
protectedvoidinitMenus() {
JMenuBar
menubar= newJMenuBar();
JMenu
menu1 = newJMenu("File");
JMenu
menu2 = newJMenu("Edit");
menubar.add(menu1);
menubar.add(menu2);
menu1.add("erster punkt");
menu1.add(new
JMenuItem
("zweiter punkt"));
JMenu
submenu= newJMenu("auswahl");
submenu.add("1. wahl");
submenu.add(newJMenuItem("2. wahl"));
menu2.add(submenu);
menu2.add("einfacher punkt");
this.setJMenuBar(menubar);
}
(c) schmiedecke 05inf1-11 GUIs27
Layout
•Everycontainerhas a
LayouterManager
object
attachedto it, whichputsthecomponentsintoposition.
•Swing's
LayouterManager
are
Absolute componentsizes, positioningusing
pixelcoordinates. No reactionto windowresizing.
NullLayout
Gridwithcomplexcells(cellcombinations)
GridBagLayout
Panel overlaywithregistertabs
CardLayout
Big centerwithoptional headerand footingrow
and right and leftbordercolumn(Center, North,
South,...)
BorderLayout
likeGrid, butonlyoneroworcolumn
BoxLayout
Rowand columnlayout withequalsizecells,
componentsfittedto cellsize
GridLayout
simplestlayout, fillingrowsfromleftto right,
usingcompontes' standardsize
FlowLayout
(c) schmiedecke 05inf1-11 GUIs28
GridLayout
window.setLayout(
newGridLayout(4,2)
);
window.add(login);
window.add(newJLabel(" "));// Dummy forGridLayout
window.add(user);
window.add(userfield);
window.add(pw);
window.add(pwfield);
window.add(ok);
(c) schmiedecke 05inf1-11 GUIs29
BorderLayout
in combinationwtihGridLayout
window.setLayout(
newBorderLayout()
);
window.add(anmeldung,BorderLayout.NORTH);
JPanelcenter=
newJPanel(newGridLayout(2,2))
;
center.add(user);
center.add(userfield);
center.add(pw);
center.add(pwfield);
window.add(center, BorderLayout.CENTER);
window.add(ok,BorderLayout.SOUTH);
(c) schmiedecke 05inf1-11 GUIs30
Insteadof CardLayout
In swing, usespecial
container
JTabbedPane
insteadof CardLayout
JTabbedPanetabbedPane= newJTabbedPane(SwingConstants.LEFT);
tabbedPane.setBackground(Color.blue);
tabbedPane.setForeground(Color.white);
JPanelfirst= newJPanel();
erstes.add(newJLabel("Ich bin Nr.1!"));
tabbedPane.addTab("erster", null, first,"Erste Karte");
tabbedPane.addTab("zweiter", null, newJPanel(),"Zweite Karte");
tabbedPane.addTab("dritter", null, newJPanel(),"Dritte Karte");
window.add(tabbedPane);
(c) schmiedecke 05inf1-11 GUIs31
Creativitytime...
•Thinkhowto setup a calculatorGUI
(c) schmiedecke 05inf1-11 GUIs32
Graphics
•Class
Graphics
: workingwithpixels.
•Everycomponentsposessesa Graphics object
describingitssize, shape, coloretc.
•Youcanadddrawingsto Graphics objectscalling
e.g.:
drawLine(intx1, inty1, intx2 inty2),
drawRect(intx, inty, intwidth, intheight)
drawOval(intx, inty, intwidth, intheight)
drawImage(Image image, intx,...)
setColor(Color c)
(c) schmiedecke 05inf1-11 GUIs33
paint()
TheVM callsa component'smethod
paint(Graphics g)
wheneverrepaintingisrequired(e.g. windowresize)
Thecomponent'sGraphics objectispassedas a parameter.
Users cancall
repaint()
to trigger
paint().
Overriding
paint()
will
permanentlychange
a component's
apperarance, e.g. addinga lineusingdrawLine()
Usually, youdrawintoemptycontainerslikeJPanelorCanvas
(c) schmiedecke 05inf1-11 GUIs34
getGraphics()
•TheComponent method
getGraphics()
yieldsthecurrentlyusedcopyof thscomponent's
Graphics object
(and null beforethecomponentispaintedforthefirsttime!)
•Youcanuseitfordrawing, too(drawLine()...)
•Butyourdrawingswill be
lost
withthenextcallof
paint()
and canbe
deleted
usingrepaint()!
(c) schmiedecke 05inf1-11 GUIs35
final JPanelpanel= newJPanel(){
publicvoid
paint
(Graphics g){
g.fillOval(20,20,10,10);
}};
protectedvoidinit() {
JButtonkreis = newJButton("Kreis");
add(kreis, BorderLayout.SOUTH);
JButtonloeschen= newJButton("löschen");
add(loeschen, BorderLayout.NORTH);
add(panel);
kreis.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
panel.getGraphics().drawOval(15,15,20,20);
}}); // draw circle
loeschen.addActionListener(newActionListener(){
publicvoidactionPerformed(ActionEvente){
repaint();
}}); // erase circle
setSize(200,200);
setVisible(true);
}
(c) schmiedecke 05inf1-11 GUIs36
...niceGUIsbutlazy!



Let'smakethemworkafterthebreak!