26

Click here to load reader

Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

  • Upload
    buidieu

  • View
    287

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

© 2010 Marty Hall

Basic SwingBasic Swing Better 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 your location.2

© 2010 Marty Hall

For live Java EE training, please see training courses at http://courses.coreservlets.com/. at http://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, gHibernate/JPA, and customized combinations of topics.

Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public

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 your location.

Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your

organization. Contact [email protected] for details.

Page 2: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Topics in This Section

• New featuresV AWT– Vs. AWT

• Basic approach• Summary of Swing componentsSummary of Swing components

– Starting points• JApplet, JFrame

– Swing equivalent of AWT components• JLabel, JButton, JPanel, JSlider

– Swing components that have no AWT equivalentSwing components that have no AWT equivalent• JColorChooser, JInternalFrame, JOptionPane, JToolBar,

JEditorPane

Other simple components– Other simple components• JCheckBox, JRadioButton, JTextField, JTextArea,

JFileChooser4

© 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 your location.5

Page 3: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

New Features vs AWT

• Many more built-in controls– Image buttons, tabbed panes, sliders, toolbars, color

choosers, HTML text areas, lists, trees, and tables.

• Increased customization of components• Increased customization of components – Border styles, text alignments, and basic drawing

features. Images can be added to almost any control. g y• A pluggable “look and feel”

– Not limited to “native” look. • Many miscellaneous small features• Many miscellaneous small features

– Built-in double buffering, tool-tips, dockable toolbars, keyboard accelerators, custom cursors, etc.

• Model-view-controller architecture– Can change internal representation of trees, lists, tables.

6

Swing vs. AWT Programming

• Naming convention– All Swing component names begin with a capital J and

follow the format JXxx. E.g., JFrame, JPanel, JApplet, JDialog, JButton. Many are just AWT names with a J.JDialog, JButton. Many are just AWT names with a J.

• Lightweight components– Most Swing components are lightweight: formed by g p g g y

drawing in the underlying window.

• Use of paintComponent for drawingC t d i d i i i tC t t i t– Custom drawing code is in paintComponent, not paint. Double buffering turned on by default.

• New Look and Feel as defaultNew Look and Feel as default– With Swing, you have to explicitly set the native look.

• Don't mix Swing and AWT in same window7

Page 4: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Classic Java Look and Feel(Metal)(Metal)

8 http://download.java.net/javadesktop/swingset3/SwingSet3.jnlp

New Java Look and Feel(Nimbus – JDK 1 6 0 10)(Nimbus – JDK 1.6.0_10)

9

Page 5: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Windows Look and Feel

10

CDE/Motif Look and Feel

11

Page 6: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Setting Native Look and Feel

• Idea– Many apps use native look, not default “Java” look– Changing is tedious, so use static method

public class WindowUtilities {public static void setNativeLookAndFeel() {

try {try {UIManager.setLookAndFeel(

UIManager.getSystemLookAndFeelClassName());} catch(Exception e) {} catch(Exception e) {

System.out.println("Error setting native LAF: "+ e);

}}}...

12

Nimbus Look and Feel

• NewI d d i JDK 1 6 0 10– Introduced in JDK 1.6.0_10

• Motivations– Original Java LAF a bit dull compared to modernOriginal Java LAF a bit dull compared to modern

interfaces– Windows LAF not updated to be consistent with Vista

and Aeroand Aero– Other LAFs did not scale well

• Nimbus based on vector graphics

B t bl• Be portable– Stick with original Java LAF if Nimbus is unavailable

• More infoMore info– http://developers.sun.com/learning/javaoneonline/

2008/pdf/TS-6096.pdf13

Page 7: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Setting Nimbus Look and Feel

public static void setNimbusLookAndFeel() {try {try {LookAndFeelInfo[] lafs =UIManager.getInstalledLookAndFeels();

for (LookAndFeelInfo laf: lafs) {for (LookAndFeelInfo laf: lafs) {if ("Nimbus".equals(laf.getName())) {UIManager.setLookAndFeel(laf.getClassName());

}}}

} catch(Exception e) {System.out.println("Error setting Nimbus LAF: " + e);y p g

}}

14

Whirlwind Tour of Basic ComponentsComponents

• Starting points– JApplet, JFrame

• Swing equivalent of AWT componentsJL b l JB JP l JSlid– JLabel, JButton, JPanel, JSlider

• New Swing componentsJColorChooser JInternalFrame JOptionPane JToolBar– JColorChooser, JInternalFrame, JOptionPane, JToolBar, JEditorPane

• Other simple componentsp p– JCheckBox, JRadioButton, JTextField, JTextArea,

JFileChooser

15

Page 8: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

© 2010 Marty Hall

Starting Windows:Starting Windows: JApplet and JFramepp

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 your location.16

Starting Point 1: JApplet

• Content pane– A JApplet contains a content pane in which to add

components. Changing other properties like the layout manager, background color, etc., also applies to themanager, background color, etc., also applies to the content pane. Access the content pane through getContentPane.

L t• Layout manager– The default layout manager is BorderLayout (as with

Frame and JFrame), not FlowLayout (as with Applet).Frame and JFrame), not FlowLayout (as with Applet). BorderLayout is really layout manager of content pane.

• Look and feel– The default look and feel is Java, so you have to

explicitly switch if you want the native look and feel.17

Page 9: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JApplet: Example Code

import java.awt.*;import javax swing *;import javax.swing. ;

public class JAppletExample extends JApplet {public void init() {p () {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"));

t t dd( JB tt ("B tt 3"))content.add(new JButton("Button 3"));}

}

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 behaviorJF l i ll h li k h Cl– JFrames close automatically when you click on the Close button (unlike AWT Frames).

• However, closing the last JFrame does not result in your g yprogram exiting the Java application. To get this behavior, call setDefaultCloseOperation(EXIT_ON_CLOSE).

– This permits the JFrame to close; however, you won’t be able to l t h l i i ht i th Wi d Li tcomplete any house cleaning as you might in the WindowListener.

So, you can still use an explicit exit listener as we did with Frame.

• Look and feel– The default look and feel is Java (Metal)

19

Page 10: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JFrame: Example Code

public class JFrameExample extends JFrame {public static void main(String[] args) {public static void main(String[] args) {JFrame frame = new JFrameExample("This is a test");frame.setVisible(true);

}

public JFrameExample(String title) {super(title);WindowUtilities setNativeLookAndFeel();WindowUtilities.setNativeLookAndFeel();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"));

t t dd( JB tt ("B tt 3"))content.add(new JButton("Button 3"));setDefaultCloseOperation(EXIT_ON_CLOSE);

}}20

© 2010 Marty Hall

New Features of SwingNew Features of Swing Components (vs. AWT)p ( )

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 your location.21

Page 11: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Swing Equivalents of AWT ComponentsComponents

• JLabel– New features: HTML content images, borders

• JButtonN f i li i– New features: icons, alignment, mnemonics

• JPanelNew feature: borders– New feature: borders

• JSlider– New features: tick marks and labelsNew features: tick marks and labels

22

JLabel

• Main new feature: HTML content– If text is "<html>...</html>", it gets rendered as HTML– HTML labels only work in JDK 1.2.2 or later, or in

Swing 1 1 1 or laterSwing 1.1.1 or later. – In JDK 1.2 the label string must begin with <html>, not

<HTML>. 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. – You must use <P> not <BR> to force a line break– You must use <P>, not <BR>, to force a line break. – Other HTML support is spotty.

• Be sure to test each HTML construct you use. Permitting th t t HTML t t t ti i ki fthe user to enter HTML text at runtime is asking for trouble.

• Other new features: images, borders23

Page 12: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JLabel: Example Code

String labelText ="<html><FONT COLOR=WHITE>WHITE</FONT> and " +<html><FONT COLOR=WHITE>WHITE</FONT> and +"<FONT COLOR=GRAY>GRAY</FONT> Text</html>";

JLabel coloredLabel =new JLabel(labelText JLabel CENTER);new JLabel(labelText, JLabel.CENTER);

...labelText =

"<ht l><B>B ld</B> d <I>It li </I> T t</ht l>""<html><B>Bold</B> and <I>Italic</I> Text</html>";JLabel boldLabel =

new JLabel(labelText, JLabel.CENTER);labelText =

"<html>The Applied Physics Laboratory is..." +"of the Johns Hopkins University." +"<P>" + ... "...</html>";

24

JLabel: Example Output

25

Page 13: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JButton

• Main new feature: icons1 C I I b i h I I1. Create an ImageIcon by passing the ImageIcon

constructor a String representing a GIF or JPG file (animated GIFs are supported!).

F l t ll tI ( tC d B () )• From an applet, call getImage(getCodeBase()…) normally, then pass resultant Image to ImageIcon.

2. Pass the ImageIcon to the JButton constructor.Alt ti l ll tI I f t th 7 ibl• Alternatively, call setIcon. In fact, there are 7 possible images (rollover images, images for when button is depressed, etc.)

• Other features• Other features– 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 Code

import java.awt.*;import javax swing *;import javax.swing.*;

public class JButtons extends JFrame {public static void main(String[] args) {public static void main(String[] args) {

JFrame frame = new JButtons();frame.setVisible(true);

}}

public JButtons() {super("Using JButton");supe ( Us g J utto );WindowUtilities.setNativeLookAndFeel();setDefaultCloseOperation(EXIT_ON_CLOSE);Container content = getContentPane();g ();content.setBackground(Color.WHITE);content.setLayout(new FlowLayout());

27

Page 14: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JButton: Example Code (Continued)(Continued)

JButton button1 = new JButton("Java");content add(button1);content.add(button1);ImageIcon cup = new ImageIcon("images/cup.gif");JButton button2 = new JButton(cup);content add(button2);content.add(button2);JButton button3 = new JButton("Java", cup);content.add(button3);JButton button4 = new JButton("Java", cup);JButton button4 new JButton( Java , cup);button4.setHorizontalTextPosition

(SwingConstants.LEFT);content.add(button4);co te t.add(butto );pack();

}}}

28

JPanel

• Main new feature: borders– Create a Border object by calling

BorderFactory.createXxxBorder. – Supply the Border object to the JPanel by means of– Supply the Border object to the JPanel by means of

setBorder.JPanel p = new JPanel();p setBorder(BorderFactory createTitledBorder("Java"));p.setBorder(BorderFactory.createTitledBorder("Java"));

• Other features: – Layout manager settingsLayout manager settings

• Can pass the layout manager to the JPanel constructor

– Setting preferred sizeTh i JC If t JP l t t lik• There is no JCanvas. If you want JPanel to act like Canvas, call setPreferredSize.

29

Page 15: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Standard Borders

• Static methods in BorderFactory– createEmptyBorder(int top, int left, int bottom, int right)

• Creates an EmptyBorder object that simply adds space (margins) around the component. ( g ) p

– createLineBorder(Color color)– createLineBorder(Color color, int thickness)

• Creates a solid-color border• Creates a solid-color border

– createTitledBorder(String title)– createTitledBorder(Border border, String title)

Th b d i t h d li l li itl id• The border is an etched line unless you explicitly provide a border style in second constructor.

– createEtchedBorder()– createEtchedBorder(Color highlight, Color shadow)

• Creates a etched line without the label

30

JPanel: Example Code

public class SixChoicePanel extends JPanel {public SixChoicePanel(String title, String[] buttonLabels)public SixChoicePanel(String title, String[] buttonLabels) {super(new GridLayout(3, 2));setBackground(Color.LIGHT_GRAY);t d ( d t t itl d d (titl ))setBorder(BorderFactory.createTitledBorder(title));

ButtonGroup group = new ButtonGroup();JRadioButton option;int halfLength = buttonLabels.length/2;int halfLength buttonLabels.length/2; for(int i=0; i<halfLength; i++) {option = new JRadioButton(buttonLabels[i]);group.add(option);add(option);option = new JRadioButton(buttonLabels[i+halfLength]);group.add(option);add(option);add(option);

}}

}31

Page 16: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JPanel: Example Output

• Left window uses createLineBorder• Right window has three SixChoicePanels

32

JSlider

• Basic use– public JSlider()– public JSlider(int orientation)

public JSlider(int min int max)– public JSlider(int min, int max)– public JSlider(int min, int max, int initialValue)– public JSlider(int orientation, int min, int max, p ( , , ,

int initialValue)

• New features: tick marks and labels– setMajorTickSpacing– setMinorTickSpacing

setPaintTicks– setPaintTicks– setPaintLabels (icons allowed as labels)

33

Page 17: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JSlider: Example Code

JSlider slider1 = new JSlider();slider1 setBorder( );slider1.setBorder(...);content.add(slider1, BorderLayout.NORTH);JSlider slider2 = new JSlider();slider2 setBorder( );slider2.setBorder(...);slider2.setMajorTickSpacing(20);slider2.setMinorTickSpacing(5);slider2.setPaintTicks(true);slider2.setPaintTicks(true);content.add(slider2, BorderLayout.CENTER);JSlider slider3 = new JSlider();slider3.setBorder(...);s de 3.set o de (...);slider3.setMajorTickSpacing(20);slider3.setMinorTickSpacing(5);slider3.setPaintTicks(true);( );slider3.setPaintLabels(true);content.add(slider3, BorderLayout.SOUTH);

34

© 2010 Marty Hall

Swing Components thatSwing Components that 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 your location.35

Page 18: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JColorChooser

• Open– Call JColorChooser.showDialog

• First argument: parent component• Second argument: title stringSecond argument: title string• Third argument: initially-selected Color

• Return value– Selected Color if “OK” chosen– null if “Cancel” chosen

36

JColorChooser:Example CodeExample Code

• 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

Page 19: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JColorChooser:Example OutputExample Output

38

Internal Frames

• MDI: Multiple Document Interface– Program has one large “desktop” pane that holds all other

windows. The other windows can be iconified (minimized) and moved around within this desktop pane,(minimized) and moved around within this desktop pane, but not moved outside the pane. Furthermore, minimizing the desktop pane hides all the contained windows as well.E l Mi ft P P i t C l D B l d– Examples: Microsoft PowerPoint, Corel Draw, Borland JBuilder, and Allaire HomeSite

• Swing Support for MDISwing Support 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

Page 20: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Using JInternalFrame

• Main constructor– public JInternalFrame(String title,

boolean resizable,boolean closeableboolean closeable,boolean maximizable,boolean iconifiable))

• Other useful methods– moveToFront – moveToBack– setSize (required!)

tL ti ( i d!)– setLocation (required!)

40

Internal Frames: Example Code

import java.awt.*;import javax swing *;import javax.swing.*;

public class JInternalFrames extends JFrame {public static void main(String[] args) {public static void main(String[] args) {

JFrame frame = new JInternalFrames();frame.setVisible(true);

}}

public JInternalFrames() {super("Multiple Document Interface");supe ( u t p e ocu e t te ace );WindowUtilities.setNativeLookAndFeel();setDefaultCloseOperation(EXIT_ON_CLOSE);Container content = getContentPane();g ();

41

Page 21: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Internal Frames: Example Code (Continued)(Continued)

JDesktopPane desktop = new JDesktopPane();desktop setBackground(Color LIGHT GRAY);desktop.setBackground(Color.LIGHT_GRAY);content.add(desktop, BorderLayout.CENTER);setSize(450, 400);for(int i=0; i<5; i++) {for(int i=0; i<5; i++) {

JInternalFrame frame= new JInternalFrame(("Internal Frame " + i),

true, true, true, true);true, true, true, true);frame.setLocation(i*50+10, i*50+10);frame.setSize(200, 150);frame.setBackground(Color.WHITE);a e.set ac g ou d(Co o . );desktop.add(frame);frame.moveToFront();frame.setVisible(true);( );

}}

}42

Internal Frames: Example OutputExample Output

43

Page 22: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JOptionPane

• Very rich class with many options for diff f di l bdifferent types of dialog boxes.

• Five main static methodsJO i P h M Di l– JOptionPane.showMessageDialog

• Icon, message, OK button

– JOptionPane.showConfirmDialogp g• Icon, message, and buttons:

OK, OK/Cancel, Yes/No, or Yes/No/Cancel

– JOptionPane showInputDialog (2 versions)– JOptionPane.showInputDialog (2 versions)• Icon, message, textfield or combo box, buttons

– JOptionPane.showOptionDialog• Icon, message, array of buttons or other components

44

JOptionPane Message Dialogs (Windows LAF)(Windows LAF)

45

Page 23: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JOptionPane Confirmation Dialogs (Java LAF)Dialogs (Java LAF)

46

JToolBar

• Acts mostly like a JPanel for buttons• Dockable: can be dragged and dropped

47

Page 24: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

JEditorPane

• Acts somewhat like a text area• Can display HTML and, if HyperLinkListener

attached, can follow links

48

Other Simple Swing ComponentsComponents

• JCheckBox– Note uppercase B

(vs. Checkbox in AWT)

• JRadioButton• JRadioButton– Use a ButtonGroup to

link radio buttons

• JTextField– Just like AWT TextField except that it does not act as a

d fi ld ( JP dFi ld f h )password field (use JPasswordField for that)

• JTextAreaPlace in JScrollPane if– Place in JScrollPane if you want scrolling

• JFileChooser49

Page 25: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

© 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 your location.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

Page 26: Basic SwingBasic Swing - Core Servletscourses.coreservlets.com/Course-Materials/pdf/java5/12-Basic-Swing.pdf · Basic SwingBasic Swing ... • Summary of Swing componentsSummary of

Summary

• Port simple AWT components to Swing by ddi J f f ladding J to front of class name

• Put custom drawing in paintComponentC ll i C b i i l– Call super.paintComponent at beginning unless you turn off double buffering

• Java look and feel is defaultJava look and feel is default– But you usually want either new (Nimbus) LAF or

native LAF

• Frames and applets use content pane– Don’t put anything directly in window

M t t t b d & i• Most components support borders & icons• Many new components

52

© 2010 Marty Hall

Questions?Questions?

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 your location.53