You are on page 1of 26

© 2009 Marty Hall

Basic Swing
Better GUI Controls
Originals of Slides and Source Code for Examples:
Customized Java EE Training:

Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.

© 2009 Marty Hall

For live Java training, please see training courses at Servlets, JSP, Struts Classic, Struts 2, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext, etc.), GWT, Java 5, Java 6, Spring, Hibernate/JPA, Hibernate/JPA and customized combinations of topics topics.
Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your Customized Java EE Training: Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. organization. Contact for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.

• New features • Basic approach • Summary of Swing components
– Starting points
• JApplet, JFrame

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

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

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

New Features
• Many more built-in controls
– Image buttons, tabbed panes, sliders, toolbars, color choosers, HTML text areas, lists, trees, and tables.

• 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
– 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.

E. JDialog.Swing vs. 7 • Don't mix Swing and AWT in same window Classic Java Look and Feel (Metal) 8 http://download. not paint. • Lightweight components – Most Swing components are lightweight: formed by g p g g y drawing in the underlying window. AWT Programming • Naming convention – All Swing component names begin with a capital J and follow the format JXxx. you have to explicitly set the native look. JButton. Many are just AWT names with a J. JApplet.jnlp . d i d i i i tC t t i t Double buffering turned on by default. JFrame..g. • Use of paintComponent for drawing –C t Custom drawing code is in paintComponent. • New Look and Feel as default – With

New Java Look and Feel (Nimbus – JDK 1 6 0 10) 1.0_10) 9 Windows Look and Feel 10 .6.

setLookAndFeel( UIManager.CDE/Motif Look and Feel 11 Setting Native Look and Feel • Many applications use native look. } catch(Exception e) { System. 12 .println("Error setting native LAF: " + e). not default “J d f l “Java” look ”l k • Changing is tedious.out.. so use static method public class WindowUtilities { public static void setNativeLookAndFeel() { try { UIManager.getSystemLookAndFeelClassName()). } } ..

0_10 d d in 1 6 0 10 • Motivations – Original Java LAF a bit dull compared to modern interfaces – Windows LAF not updated to be consistent with Vista and Aero – Other LAFs did not scale well • Nimbus based on vector graphics • B portable Be t bl – Stick with original Java LAF if Nimbus is unavailable • More info – http://developers. y p g } } 14 .getInstalledLookAndFeels().getClassName()).getName())) { UIManager.pdf 13 Setting Nimbus Look and Feel public static void setNimbusLookAndFeel() { try { LookAndFeelInfo[] lafs = UIManager.out.println("Error setting Nimbus LAF: " + e).com/learning/javaoneonline/ 2008/pdf/TS-6096.sun.6.equals(laf. } } } catch(Exception e) { System.Nimbus Look and Feel • New –I Introduced i JDK 1. for (LookAndFeelInfo laf: lafs) { if ("Nimbus".setLookAndFeel(laf.

JInternalFrame. JTextArea.. JFileChooser 15 Starting Point 1: JApplet • Content pane – A JApplet contains a content pane in which to add components. JRadioButton. JOptionPane JToolBar.Whirlwind Tour of Basic Components • Starting points – JApplet. JTextField. JFrame • Swing equivalent of AWT components – JL b l JB JLabel. JToolBar JColorChooser. JSlider • New Swing components – JColorChooser JInternalFrame JOptionPane. BorderLayout is really layout manager of content pane. • Look and feel 16 – The default look and feel is Java (Metal). JP l JSlid JPanel. Changing other properties like the layout manager. JButton. • L Layout manager t – The default layout manager is BorderLayout (as with Frame and JFrame). so you have to explicitly switch the look and feel if you want the native look. Access the content pane through getContentPane. etc. not FlowLayout (as with Applet). JEditorPane • Other simple components p p – JCheckBox. background color. also applies to the content pane. .

content.JApplet: Example Code import java.setNativeLookAndFeel(). public class JAppletExample extends JApplet { public void init() { WindowUtilities.*.setLayout(new FlowLayout()).add(new JButton("Button 2")). content.swing.setBackground(Color. content.awt. javax.add(new JButton("Button 1")).WHITE). content. } } 17 JApplet: Example Output 18 . import javax swing *. ( ( )).add(new JButton("Button 3")).*. content. Container content = getContentPane().

closing the last JFrame does not result in your p g y program exiting the Java g application.add(new JButton("Button 1")). your “main” JFrame still needs a WindowListener to call System. f.3 or later. alternatively.setLayout(new FlowLayout()).exit. content. if using JDK 1.setVisible(true). import javax.setNativeLookAndFeel().add(new JButton("Button 2")). javax swing . content. content.setSize(400.Starting Point 2: JFrame • Content pane – JFrame uses content pane in same way as does JApplet. Windo Utilities setNati eLookAndFeel() JFrame f = new JFrame("This is a test"). however.swing. Or.add(new JButton("Button 3")).setBackground(Color. f. So. f. Container content = f getContentPane(). • Auto-close behavior – JF JFrames close automatically when you click on the Close l i ll h li k h Cl button (unlike AWT Frames). content.getContentPane(). However. This permits the JFrame to close.awt. 150).*. you won’t be able to complete any house cleaning as you might in the WindowListener WindowListener. you can call setDefault setDefaultCloseOperation(EXIT_ON_CLOSE). } } 20 . f. • Look and feel 19 – The default look and feel is Java (Metal) JFrame: Example Code import java.*. ( ( )) content. public class JFrameExample { public static void main(String[] args) { WindowUtilities.WHITE).addWindowListener(new ExitListener()).

awt. public class ExitListener extends WindowAdapter { public void windowClosing(WindowEvent event) { System.*.event.JFrame Helper: ExitListener import java. import java awt event *. java.awt.exit(0).*. } } 21 JFrame: Example Output 22 .

or in Swing 1 1 1 or later 1. It is case-insensitive in JDK 1. alignment. not <HTML>.4. borders .2 or later. – JLabel fonts are ignored if HTML is used. If you use HTML.2. Permitting the th user to enter HTML text at runtime is asking for t t t t t ti i ki f trouble. – In JDK 1.</html>". it gets rendered as HTML – HTML labels only work in JDK 1. – You must use <P> not <BR> to force a line break <P>.3 and 1.2 the label string must begin with <html>. 24 • Other new features: images. • Be sure to test each HTML construct you use.. break.1 later.Swing Equivalents of AWT Components • JLabel – New features: HTML content images. all font control must be performed by HTML.. borders • JButton –N f New features: i icons. – Other HTML support is spotty.1. mnemonics li i • JPanel – New feature: borders • JSlider – New features: tick marks and labels 23 JLabel • Main new feature: HTML content – If text is "<html>. <BR>.

JLabel(labelText.." + "of the Johns Hopkins University. labelText = "<html><B>Bold</B> "<ht l><B>B ld</B> and <I>It li </I> T t</ht l>" d <I>Italic</I> Text</html>". JLabel. JLabel.JLabel: Example Code String labelText = "<html><FONT COLOR=WHITE>WHITE</FONT> and " + <html><FONT "<FONT COLOR=GRAY>GRAY</FONT> Text</html>"...CENTER)." + "<P>" + . . 25 JLabel: Example Output 26 .. labelText = "<html>The Applied Physics Laboratory is.. ". JLabel coloredLabel = new JLabel(labelText JLabel CENTER)... JLabel boldLabel = new JLabel(labelText.CENTER)..</html>".

) d d t ) 2. • • From an applet. content. import javax swing *. do Ut t es. etc. Container content = getContentPane(). } public JButtons() { super("Using JButton").setBackground(Color. normally then pass resultant Image to ImageIcon ImageIcon. images for when button is g g images ( depressed.setNativeLookAndFeel().setLayout(new FlowLayout()). 27 JButton: Example Code import java. content.WHITE). WindowUtilities. call setIcon. public class JButtons extends JFrame { public static void main(String[] args) { new JButtons().*. • Other features – – – HTML content as with JLabel Alignment: l ti of image with respect to text Ali t location f i ith tt t t Mnemonics: keyboard accelerators that let you use AltsomeChar to trigger the button. 1 Create an ImageIcon by passing the ImageIcon constructor a String representing a GIF or JPG file (animated GIFs are supported!).set at e oo d ee (). there are 7 possible g (rollover images.awt. javax.swing.JButton • Main new feature: icons 1. Pass the ImageIcon to the JButton constructor. g ( ). In fact. 28 . call getImage(getCodeBase()…) normally. addWindowListener(new ExitListener()). Alternatively.*.

add(button4). } } 29 JButton: Example Output 30 . setVisible(true). content. content.add(butto ).setHorizontalTextPosition (SwingConstants. JButton button3 = new JButton("Java". pack().gif"). button4.LEFT). JButton button2 = new JButton(cup).add(button1). content add(button2). content. content.JButton: Example Code (Continued) JButton button1 = new JButton("Java"). ImageIcon cup = new ImageIcon("images/cup. co te t. content add(button1). JButton( Java . cup). JButton button4 = new JButton("Java". cup).add(button2).add(button3).

• Other features: – Layout manager settings • Can pass the layout manager to the JPanel constructor – Setting preferred size • Th There is no JCanvas. JPanel p = new JPanel(). int right) • Creates an EmptyBorder object that simply adds space ( (margins) around the component. If you want JPanel to act like i JC t JP lt t lik Canvas. Color shadow) • Creates a etched line without the label 32 .createXxxBorder. p setBorder(BorderFactory createTitledBorder("Java")). String title) • Th border is an etched line unless you explicitly provide a The b d i t h d li l li itl id border style in second constructor. int bottom.JPanel • Main new feature: borders – Create a Border object by calling BorderFactory. int left. int thickness) • Creates a solid-color border – createTitledBorder(String title) – createTitledBorder(Border border. – Supply the Border object to the JPanel by means of setBorder. – createEtchedBorder() – createEtchedBorder(Color highlight. p. 31 Standard Borders • Static methods in BorderFactory – createEmptyBorder(int top.setBorder(BorderFactory.createTitledBorder("Java")). g ) p – createLineBorder(Color color) – createLineBorder(Color color. call setPreferredSize.

JPanel: Example Code public class SixChoicePanel extends JPanel { public SixChoicePanel(String title. setBorder(BorderFactory. for(int i=0. int halfLength = buttonLabels. option = new JRadioButton(buttonLabels[i+halfLength]).add(option).LIGHT_GRAY). JRadioButton option. add(option). 2)).length/2. i<halfLength. setBackground(Color. String[] buttonLabels) { super(new GridLayout(3. group. t d ( d t t itl d d (titl )) ButtonGroup group = new ButtonGroup().createTitledBorder(title)). add(option). } } } 33 JPanel: Example Output • Left window uses createLineBorder • Right window has three SixChoicePanels 34 . i++) { option = new JRadioButton(buttonLabels[i]). group.add(option).

int initialValue) setMajorTickSpacing setMinorTickSpacing setPaintTicks setPaintLabels (icons allowed as labels) • New features: tick marks and labels – – – – 35 JSlider: Example Code JSlider slider1 = new JSlider(). slider3.setMajorTickSpacing(20). slider2. BorderLayout. 36 . slider2. int max) min public JSlider(int min.set o de (.).). ..setBorder(.setMinorTickSpacing(5). content. JSlider slider2 = new JSlider()..setMajorTickSpacing(20).setMinorTickSpacing(5).add(slider3.NORTH).).setBorder(. content.. BorderLayout. slider1 setBorder( ).setPaintTicks(true).CENTER). int max.SOUTH).setBorder(.add(slider1.. ( . slider3. int min.setPaintTicks(true).. BorderLayout. slider1.add(slider2. int max. . slider2. slider3. content.. s de 3. int initialValue) p public JSlider(int orientation..).setPaintLabels(true). slider3. slider3. slider2. slider2 setBorder( ).JSlider • Basic use – – – – – public JSlider() public JSlider(int orientation) public JSlider(int min. ( ).. JSlider slider3 = new JSlider().

Motif (Windows Motif.showDialog • First argument: parent component • Second argument: title string • Third argument: initially-selected Color • Return value – Selected Color if "OK" chosen – null if "Cancel" chosen 38 . Java LAF) 37 JColorChooser • Open – Call JColorChooser.JSlider: Example Output (Windows.

JColorChooser: Example Code • Button that lets you change color of window public void actionPerformed(ActionEvent e) { Color bgColor = JColorChooser.setBackground(bgColor).showDialog (this. getBackground()). if (bgColor != null) getContentPane(). Choose Color "Choose Background Color". tC t tP () tB k d(b C l ) } 39 JColorChooser: Example Output 40 .

but not moved outside the pane. except that it is constrained to stay inside the JDesktopPane. – JInternalFrame 41 • Acts mostly like a JFrame. boolean iconifiable) ) • Other useful methods – – – – 42 moveToFront moveToBack setSize (required!) setLocation (required!) tL ti ( i d!) . Corel Draw. –E Examples: Microsoft PowerPoint. minimizing the desktop pane hides all the contained windows as well.Internal Frames • MDI: Multiple Document Interface – Program has one large “desktop” pane that holds all other windows. boolean resizable. Furthermore. and Allaire HomeSite • Swing Support for MDI – JDesktopPane • Serves as a holder for the other windows. boolean closeable closeable. Using JInternalFrame • Main constructor – public JInternalFrame(String title. boolean maximizable. The other windows can be iconified (minimized) and moved around within this desktop pane. Borland l Mi ft P P i t C lD B l d JBuilder.

add(desktop. addWindowListener(new ExitListener()).*.WHITE). Container content = getContentPane(). (). setSize(450. g ().event.swing. 43 Internal Frames: Example Code (Continued) JDesktopPane desktop = new JDesktopPane().setVisible(true).awt. true). frame.*. true.setSize(200. BorderLayout.setBackground(Color. frame. te ace ). frame.moveToFront(). import java awt event *. 150). public class JInternalFrames extends JFrame { public static void main(String[] args) { new JInternalFrames().*. 400). desktop. i++) { JInternalFrame frame = new JInternalFrame(("Internal Frame " + i). frame. WindowUtilities. content.WHITE).CENTER). true.setBackground(Color.add(frame).setBackground(Color. } setVisible(true). import javax. a e. desktop setBackground(Color WHITE). ).Internal Frames: Example Code import java. content. } } 44 . true.awt. desktop. for(int i=0. i*50+10).WHITE).setNativeLookAndFeel(). java. } public JInternalFrames() { supe ( u t p e ocu e t super("Multiple Document Interface"). frame.setLocation(i*50+10. i<5.set ac g ou d(Co o .

message.showInputDialog • Icon. and buttons: OK. message.showConfirmDialog p g • Icon. buttons – JOptionPane. array of buttons or other components 46 . diff f di l b • Five main static methods – JO i P JOptionPane. message.Internal Frames: Example Output 45 JOptionPane • Very rich class with many options for different types of dialog boxes. or Yes/No/Cancel – JOptionPane showInputDialog (2 versions) JOptionPane.showOptionDialog • Icon. textfield or combo box. OK/Cancel. Yes/No. message. OK button – JOptionPane.showMessageDialog h M Di l • Icon.

JOptionPane Message Dialogs (Windows LAF) 47 JOptionPane Confirmation Dialogs (Java LAF) 48 .

if HyperLinkListener attached. can follow links 50 .JToolBar • Acts mostly like a JPanel for buttons • Dockable: can be dragged and dropped 49 JEditorPane • Acts somewhat like a text area • Can display HTML and.

html – Very useful summary of almost all Swing components t – Gives code examples – Includes graphical table showing each 52 . Checkbox in AWT) • JRadioButton – Use a ButtonGroup to link radio buttons • JTextField – Just like AWT TextField except that it does not act as a password fi ld (use JPasswordField for that) d field ( JP dFi ld f h ) • JTextArea – Place in JScrollPane if you want scrolling 51 • JFileChooser More Info • Sun Java Tutorial – books/tutorial/uiswing/ components/index.sun.Other Simple Swing Components • JCheckBox – Note uppercase B (vs.

At public venues or onsite at your location. Ajax.0. JSF 1.paintComponent at beginning unless you turn Call i C b i i l off double buffering • Java 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 components support borders & icons Most t tb d i • Many new components 53 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.x & JSF 2. Hibernate/JPA. Spring. . 54 Servlets.Summary • Port simple AWT components to Swing by adding J to front of class name ddi f f l • Put custom drawing in paintComponent – C ll super. GWT. Struts Classic & Struts 2. Developed and taught by well-known author and developer.coreservlets. Java 5 & 6.