12 Basic Swing
-
Upload
harsh-singh -
Category
Documents
-
view
28 -
download
1
description
Transcript of 12 Basic Swing
-
7/14/2019 12 Basic Swing
1/26
2010 Marty Hall
wBetter GUI Controls
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/java5.html
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.2
2010 Marty Hall
For live Java EE training, please see training courses
at htt ://courses.coreservlets.com/.Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,Hibernate/JPA, and customized combinations of topics.
Taught by the author ofCore Servlets and JSP, More
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.
, .venues, or customized versions can be held on-site at your
organization. Contact [email protected] for details.
-
7/14/2019 12 Basic Swing
2/26
Topics in This Section
New features s.
Basic approach
Starting points JApplet, JFrame
Swing equivalent of AWT components JLabel, JButton, JPanel, JSlider
JColorChooser, JInternalFrame, JOptionPane, JToolBar,
JEditorPane er s mp e componen s
JCheckBox, JRadioButton, JTextField, JTextArea,JFileChooser
4
2010 Marty Hall
Overview
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.5
-
7/14/2019 12 Basic Swing
3/26
New Features vs AWT
Many more built-in controls Image buttons, tabbed panes, sliders, toolbars, color
choosers, HTML text areas, lists, trees, and tables.
Border styles, text alignments, and basic drawingfeatures. Images can be added to almost any control.
A pluggable look and feelNot limited to native look.
Built-in double buffering, tool-tips, dockable toolbars,
keyboard accelerators, custom cursors, etc.
Model-view-controller architectureCan change internal representation of trees, lists, tables.
6
Swing vs. AWT Programming
Naming conventionAll Swing component names begin with a capital J and
follow the format JXxx. E.g., JFrame, JPanel, JApplet,JDialo JButton. Man are ust AWT names with a J.
Lightweight components
Most Swing components are lightweight: formed bydrawing in the underlying window.
Use of paintComponent for drawing us om raw ng co e s n pa n omponen , no pa n .
Double buffering turned on by default.
With Swing, you have to explicitly set the native look.
Don't mix Swing and AWT in same window7
-
7/14/2019 12 Basic Swing
4/26
Classic Java Look and Feel
8 htt ://download. ava.net/ avadeskto /swin set3/Swin Set3. nl
New Java Look and Feel. . _
9
-
7/14/2019 12 Basic Swing
5/26
Windows Look and Feel
10
CDE/Motif Look and Feel
11
-
7/14/2019 12 Basic Swing
6/26
Setting Native Look and Feel
IdeaMany apps use native look, not default Java look
Changing is tedious, so use static method
public class WindowUtilities {public static voidsetNativeLookAndFeel() {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());catch Exce tion eSystem.out.println("Error setting native LAF: "
+ e);
}...
12
Nimbus Look and Feel
New ntro uce n . . _
Motivations
interfacesWindows LAF not updated to be consistent with Vista
Other LAFs did not scale well Nimbus based on vector graphics
e por a eStick with original Java LAF if Nimbus is unavailable
http://developers.sun.com/learning/javaoneonline/
2008/pdf/TS-6096.pdf13
-
7/14/2019 12 Basic Swing
7/26
Setting Nimbus Look and Feel
public static void setNimbusLookAndFeel() {
LookAndFeelInfo[] lafs =
UIManager.getInstalledLookAndFeels();for LookAndFeelInfo laf: lafs
if ("Nimbus".equals(laf.getName())) {
UIManager.setLookAndFeel(laf.getClassName());
}
}
} catch(Exception e) {
System.out.println("Error setting Nimbus LAF: " + e);
}
}
14
Whirlwind Tour of Basic
Starting points JApplet, JFrame
Swing equivalent of AWT components a e , utton, ane , er
New Swing components , , , ,
JEditorPane
Other simple components JCheckBox, JRadioButton, JTextField, JTextArea,
JFileChooser
15
-
7/14/2019 12 Basic Swing
8/26
2010 Marty Hall
JApplet and JFrame
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.16
Starting Point 1: JApplet
Content paneA JApplet contains a content pane in which to add
components. Changing other properties like the layoutmana er back round color etc. also a lies to thecontent pane. Access the content pane throughgetContentPane.
ayou managerThe default layout manager is BorderLayout (as with
, .BorderLayout is really layout manager of content pane.
Look and feelThe default look and feel is Java, so you have to
explicitly switch if you want the native look and feel.17
-
7/14/2019 12 Basic Swing
9/26
JApplet: Example Code
import java.awt.*;
*. .
public class JAppletExample extends JApplet {public void init() {WindowUtilities.setNativeLookAndFeel();Container content = getContentPane();content.setBackground(Color.WHITE);content.setLayout(new FlowLayout());
content.add(new JButton("Button 1"));content.add(new JButton("Button 2"));con en .a new u on u on ;
}
}
18
WindowUtilities is a class I wrote: download it from the Web site.
The code for setNativeLookAndFeel was shown on an earlier slide.
Starting Point 2: JFrame
Content pane JFrame uses content pane in same way as does JApplet.
Auto-close behavior rames c ose automat ca y w en you c c on t e ose
button (unlike AWT Frames).
However, closing the last JFrame does not result in yourprogram exiting the Java application. To get this behavior,call setDefaultCloseOperation(EXIT_ON_CLOSE).
This permits the JFrame to close; however, you wont be able tocomp ete any ouse c ean ng as you m g t n t e n ow stener.So, you can still use an explicit exit listener as we did with Frame.
Look and feelThe default look and feel is Java (Metal)
19
-
7/14/2019 12 Basic Swing
10/26
JFrame: Example Code
public class JFrameExample extends JFrame {ublic static void main Strin ar sJFrame frame = new JFrameExample("This is a test");
frame.setVisible(true);}
public JFrameExample(String title) {super(title);
.setSize(300, 100);Container content = getContentPane();content.setBackground(Color.WHITE);content.setLayout(new FlowLayout());content.add(new JButton("Button 1"));
content.add(new JButton("Button 2"));con en .a new u on u on ;setDefaultCloseOperation(EXIT_ON_CLOSE);
}20
2010 Marty Hall
Components (vs. AWT)
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.21
-
7/14/2019 12 Basic Swing
11/26
Swing Equivalents of AWT
JLabelNew features: HTML content images, borders
JButton ew eatures: cons, a gnment, mnemon cs
JPanel
JSlider
22
JLabel
Main new feature: HTML content If text is "...", it gets rendered as HTML
HTML labels only work in JDK 1.2.2 or later, or in. . .
In JDK 1.2 the label string must begin with , not
. It is case-insensitive in JDK 1.3 and 1.4. JLabel fonts are ignored if HTML is used. If you use
HTML, all font control must be performed by HTML.
, , .
Other HTML support is spotty. Be sure to test each HTML construct you use. Permitting
e user o en er ex a run me s as ng ortrouble.
Other new features: ima es borders23
-
7/14/2019 12 Basic Swing
12/26
JLabel: Example Code
String labelText =" ""GRAY Text";
JLabel coloredLabel =, .
...labelText =" m >B>Bo < B> an I a c< I> Tex m >";
JLabel boldLabel =new JLabel(labelText, JLabel.CENTER);
labelText ="The Applied Physics Laboratory is..." +
"of the Johns Hopkins University." +"
" + ... "... /html>";
24
JLabel: Example Output
25
-
7/14/2019 12 Basic Swing
13/26
JButton
Main new feature: icons. reate an mage con y pass ng t e mage con
constructor a String representing a GIF or JPG file(animated GIFs are supported!). rom an app e , ca ge mage ge o e ase
normally, then pass resultant Image to ImageIcon.
2. Pass the ImageIcon to the JButton constructor. erna ve y, ca se con. n ac , ere are poss e
images (rollover images, images for when button isdepressed, etc.)
HTML content as with JLabel
Alignment: location of image with respect to text Mnemonics: keyboard accelerators that let you use Alt-
someChar to trigger the button.26
JButton: Example Codeimport java.awt.*;
*. .
public class JButtons extends JFrame {
JFrame frame = new JButtons();frame.setVisible(true);
public JButtons() {su er "Usin JButton"
WindowUtilities.setNativeLookAndFeel();setDefaultCloseOperation(EXIT_ON_CLOSE);Container content = etContentPane();content.setBackground(Color.WHITE);content.setLayout(new FlowLayout());
27
-
7/14/2019 12 Basic Swing
14/26
JButton: Example Code
JButton button1 = new JButton("Java");.
ImageIcon cup = new ImageIcon("images/cup.gif");
JButton button2 = new JButton(cup);.
JButton button3 = new JButton("Java", cup);content.add(button3);
= " "button4.setHorizontalTextPosition
(SwingConstants.LEFT);content.add button4
pack();
}}
28
JPanel
Main new feature: bordersCreate a Border object by calling
BorderFactory.createXxxBorder.
setBorder.
JPanel p = new JPanel();
. .
Other features:La out mana er settin s
Can pass the layout manager to the JPanel constructor
Setting preferred size ere s no anvas. you wan ane o ac e
Canvas, call setPreferredSize.
29
-
7/14/2019 12 Basic Swing
15/26
Standard Borders
Static methods in BorderFactory createEmptyBorder(int top, int left, int bottom, int right)
Creates an EmptyBorder object that simply adds spacemar ins around the com onent.
createLineBorder(Color color)createLineBorder(Color color, int thickness)
-
createTitledBorder(String title)createTitledBorder(Border border, String title)
e or er s an e c e ne un ess you exp c y prov e aborder style in second constructor.
createEtchedBorder()createEtchedBorder(Color highlight, Color shadow)
Creates a etched line without the label
30
JPanel: Example Codepublic class SixChoicePanel extends JPanel {
ublic SixChoicePanel Strin title Strin buttonLabels{super(new GridLayout(3, 2));setBackground(Color.LIGHT_GRAY);se Bor er Bor erFac ory.crea eT e Bor er e ;ButtonGroup group = new ButtonGroup();JRadioButton option;
= .for(int i=0; i
-
7/14/2019 12 Basic Swing
16/26
JPanel: Example Output
Left window uses createLineBorder
Right window has three SixChoicePanels
32
JSlider
Basic usepublic JSlider()
public JSlider(int orientation)
,
public JSlider(int min, int max, int initialValue)
ublic JSlider int orientation int min int maxint initialValue)
New features: tick marks and labels setMajorTickSpacing
setMinorTickSpacing
setPaintLabels (icons allowed as labels)
33
-
7/14/2019 12 Basic Swing
17/26
JSlider: Example Code
JSlider slider1 = new JSlider();. ...
content.add(slider1, BorderLayout.NORTH);
JSlider slider2 = new JSlider();. ...
slider2.setMajorTickSpacing(20);slider2.setMinorTickSpacing(5);
content.add(slider2, BorderLayout.CENTER);JSlider slider3 = new JSlider();slider3.setBorder ...slider3.setMajorTickSpacing(20);
slider3.setMinorTickSpacing(5);slider3.setPaintTicks(true);slider3.setPaintLabels(true);content.add(slider3, BorderLayout.SOUTH);
34
2010 Marty Hall
Were Not in AWT
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.35
-
7/14/2019 12 Basic Swing
18/26
JColorChooser
OpenCall JColorChooser.showDialog
First argument: parent component
Third argument: initially-selected Color
Return valueSelected Color if OK chosen
null if Cancel chosen
36
JColorChooser:
Button that lets you change color of window
public void actionPerformed(ActionEvent e) {Color bgColor= JColorChooser.showDialog
(this,
"Choose Background Color",getContentPane().getBackground());
if (bgColor != null)getContentPane().setBackground(bgColor);
}
37
-
7/14/2019 12 Basic Swing
19/26
JColorChooser:
38
Internal Frames
MDI: Multiple Document InterfaceProgram has one large desktop pane that holds all other
windows. The other windows can be iconifiedminimized and moved around within this deskto ane
but not moved outside the pane. Furthermore, minimizingthe desktop pane hides all the contained windows as well.
xamp es: croso ower o n , ore raw, or anJBuilder, and Allaire HomeSite
Swin Su ort for MDI JDesktopPane
Serves as a holder for the other windows.
JInternalFrame Acts mostly like a JFrame, except that it is constrained to
stay inside the JDesktopPane.39
-
7/14/2019 12 Basic Swing
20/26
Using JInternalFrame
Main constructorpublic JInternalFrame(String title,
boolean resizable,,
boolean maximizable,
boolean iconifiable
Other useful methodsmoveToFront
moveToBack
setSize (required!) se oca on requ re
40
Internal Frames: Example Codeimport java.awt.*;
*. .
public class JInternalFrames extends JFrame {
JFrame frame = new JInternalFrames();frame.setVisible(true);
public JInternalFrames() {su er "Multi le Document Interface"
WindowUtilities.setNativeLookAndFeel();setDefaultCloseOperation(EXIT_ON_CLOSE);Container content = etContentPane();
41
-
7/14/2019 12 Basic Swing
21/26
Internal Frames: Example Code
JDesktopPane desktop = new JDesktopPane();. . _
content.add(desktop, BorderLayout.CENTER);
setSize(450, 400);=
JInternalFrame frame= new JInternalFrame(("Internal Frame " + i),
frame.setLocation(i*50+10, i*50+10);frame.setSize(200, 150);frame.setBack round Color.WHITEdesktop.add(frame);
frame.moveToFront();frame.setVisible(true);}
}
}42
Internal Frames:
43
-
7/14/2019 12 Basic Swing
22/26
JOptionPane
Very rich class with many options fordifferent types of dialog boxes.
Five main static methods pt on ane.s ow essage a og
Icon, message, OK button
JO tionPane.showConfirmDialo Icon, message, and buttons:
OK, OK/Cancel, Yes/No, or Yes/No/Cancel
. Icon, message, textfield or combo box, buttons
JOptionPane.showOptionDialog Icon, message, array of buttons or other components
44
JOptionPane Message Dialogs
45
-
7/14/2019 12 Basic Swing
23/26
JOptionPane Confirmation
46
JToolBar
Acts mostly like a JPanel for buttons
Dockable: can be dragged and dropped
47
-
7/14/2019 12 Basic Swing
24/26
JEditorPane
Acts somewhat like a text area
Can display HTML and, if HyperLinkListener
attached, can follow links
48
Other Simple Swing
JCheckBoxNote uppercase B
(vs. Checkbox in AWT)
Use a ButtonGroup to
link radio buttons JTextField
Just like AWT TextField except that it does not act as apasswor e use asswor e or t at
JTextArea
you want scrolling
JFileChooser49
-
7/14/2019 12 Basic Swing
25/26
2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.50
More Info
Sun Java Tutorial http://java.sun.com/docs/books/tutorial/ui/features/components.html
Very useful summary of most Swing components
Gives code examples
This link forwards to a URL at
oracle.com, but the original
link is still valid.
Includes graphical table showing each
51
-
7/14/2019 12 Basic Swing
26/26
Summary
Port simple AWT components to Swing byadding J to front of class name
Put custom drawing in paintComponent a super.pa nt omponent at eg nn ng un ess you turn
off double buffering
But you usually want either new (Nimbus) LAF or
native LAF
Frames and applets use content pane
Dont put anything directly in window os componen s suppor or ers cons
Many new components52
2010 Marty Hall
u