Java.net - the Source for Java(tm) Technology Collaboration

Similar documents
Java. GUI building with the AWT

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

GUI Event Handlers (Part I)

Contents. iii Copyright 1998 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services August 1998, Revision B

Introduction to the JAVA UI classes Advanced HCI IAT351

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Starting In Java With JPT in Eclipse

Swing from A to Z Some Simple Components. Preface

Contents Introduction 1

Programming Languages and Techniques (CIS120)

CS 11 java track: lecture 3

Part 3: Graphical User Interface (GUI) & Java Applets

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

KF5008 Program Design & Development. Lecture 1 Usability GUI Design and Implementation

Programming Languages and Techniques (CIS120)

SD Module-1 Advanced JAVA

Java Swing Introduction

CS Exam 1 Review Suggestions

Chapter Two Bonus Lesson: JavaDoc

SD Module-1 Advanced JAVA. Assignment No. 4

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

Core Java Syllabus. Pre-requisite / Target Audience: C language skills (Good to Have)

Swing from A to Z Using Focus in Swing, Part 2. Preface

Packages: Putting Classes Together

COMP19612 exam performance feedback 2014

Graphical User Interface (GUI)

GUI Applications. Let s start with a simple Swing application in Java, and then we will look at the same application in Jython. See Listing 16-1.

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Queens College, CUNY Department of Computer Science. CS 212 Object-Oriented Programming in Java Practice Exam 2. CS 212 Exam 2 Study Guide

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

Educational Fusion. Implementing a Production Quality User Interface With JFC

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Hanley s Survival Guide for Visual Applications with NetBeans 2.0 Last Updated: 5/20/2015 TABLE OF CONTENTS

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

MIT AITI Swing Event Model Lecture 17

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

Creating Professional Swing UIs Using the NetBeans GUI Builder

Window Interfaces Using Swing Objects

CS 11 java track: lecture 1

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

Java - Applications. The following code sets up an application with a drop down menu, as yet the menu does not do anything.

DHANALAKSHMI SRINIVASAN COLLEGE OF ENGINEERING AND TECHNOLOGY ACADEMIC YEAR (ODD SEM)

Programming Languages and Techniques (CIS120)

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Introduction to Graphical User Interfaces (GUIs) Lecture 10 CS2110 Fall 2008

CHAPTER 2. Java Overview

Graphical User Interfaces (GUIs)

Commands. Written commands can be reused, cataloged, etc. Sometimes they also contain "undo" commands, too.

Introduction to Graphical Interface Programming in Java. Introduction to AWT and Swing

Programming Languages and Techniques (CIS120e)

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Window Interfaces Using Swing Objects

Introduction to Java

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

Widgets. Widgets Widget Toolkits. User Interface Widget

CSC207 Week 4. Larry Zhang

CSE 331 Software Design & Implementation

JavaFX Basics. Liang, Introduction to Java Programming, Tenth Edition, (c) 2015 Pearson Education, Inc. All rights reserved. 1.

MARS AREA SCHOOL DISTRICT Curriculum TECHNOLOGY EDUCATION

This page intentionally left blank

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Introduction. Overview of the Course on Java. Overview of Part 1 of the Course

CS11 Java. Fall Lecture 4

JavaFX. JavaFX Overview Release E

Widgets. Overview. Widget. Widgets Widget toolkits Lightweight vs. heavyweight widgets Swing Widget Demo

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applets. public class Buttons extends Applet implements ActionListener

1005ICT Object Oriented Programming Lecture Notes

G51PRG: Introduction to Programming Second semester Applets and graphics

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Widget Toolkits CS MVC

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Lecture 19 GUI Events

Swinging from the Outside

Decisions: Logic Java Programming 2 Lesson 7

Building a GUI in Java with Swing. CITS1001 extension notes Rachel Cardell-Oliver

Java Programming Constructs Java Programming 2 Lesson 1

Use Case 2: Extending object/application to support a new object attribute and a validation for that attribute using either Scripting or Java.

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Java Applets / Flash

Multimedia-Programmierung Übung 3

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Essential Series. Springer-Verlag London Ltd.

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Graphic User Interfaces. - GUI concepts - Swing - AWT

Core Java SYLLABUS COVERAGE SYLLABUS IN DETAILS

Core JAVA Training Syllabus FEE: RS. 8000/-

Graphical User Interface (GUI)

UI Software Organization

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

JUnit Test Patterns in Rational XDE

User interfaces and Swing

B2.52-R3: INTRODUCTION TO OBJECT-ORIENTED PROGRAMMING THROUGH JAVA

Java Programming Lecture 6

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Transcription:

java.net > All Articles > http://today.java.net/pub/a/today/2006/02/21/building-guis-with-swixml.html Building GUIs with SwiXml by Joshua Marinacci 02/21/2006 Contents The Layout Problem What is SwiXml? A Simple Example SwiXml and Actions Using XInclude Custom Components Conclusion Resources Layout has always been a major weak point of the Swing toolkit. At the API level, Swing supports virtually any layout you can imagine, but in practice, the default layout managers leave much to be desired. Over the years, enterprising developers have created a variety of utility classes to make the job easier, but recent work on the problem suggests that the best way to lay out a Swing GUI is to remove layout from the Java code altogether, either through a visual builder like Matisse in NetBeans 5.0 or by using a language other than Java to specify the GUI. One common solution is to use XML that completely separates GUI construction from program logic. This article will introduce an open source library, SwiXml, and show you how to construct your Swing user interfaces faster and more easily than ever before. The Layout Problem Building on its AWT foundations, Swing has very powerful support for creating complicated UI designs. Using a standard layout manager like GridBagLayout or SpringLayout, a developer can build an attractive interface that automatically accounts for different platform component sizes, fonts, and languages. You can even create your own custom layout manager for tricky cases like maintaining a fixed ratio. With the right layout manager, you can do almost anything. In practice however, as the humorous animation "Totally Gridbag" shows, Swing layout can be a pain to use. GridBagLayout code is typically verbose and annoying to read after the fact. SpringLayout was intended for visual GUI builders, so coding it by hand is extremely difficult. Over time, layout code often becomes unwieldy, resulting in ugly UIs that break on different platforms. This is the opposite of progress. There has to be a better way. In recent years, many developers have decided that it is a good practice to separate the GUI layout from event handling and program logic. This keeps the program logic cleaner and allows the layout to be maintained separately, often by a different developer. Some have gone a step further to specify layout in a language other than Java. These days, the natural choice for any new language is of course XML, and a quick internet search for "java xml gui layout" will return many commercial and open source layout products. One of the best is SwiXml, a tiny but powerful library that transforms simple XML descriptions into attractive user interfaces. What Is SwiXml? SwiXml is a small Java library created by Wolf Paulus in 2003 to produce Swing GUIs from a small XML language. SwiXml doesn't introduce any new layout managers or component classes. Instead, it directly operates on the Swing classes using reflection. This means that the XML syntax is easy to learn for anyone used to the Swing API. It also has the side benefit of keeping the library very small (under 60k, plus the JDOM.jar), which makes application deployment a pleasant experience. A Simple Example Before I get deeper into the syntax and mechanics of SwiXml, I'd like to show you a short example to get a feel for how it works. This is a very simple XML file that will create a frame with one text field and a button: HelloWorld.xml <?xml version="1.0" encoding="utf-8"?> <frame size="300,100"> <label constraints="borderlayout.center" text="hello World"/> <button id="quit" constraints="borderlayout.south" text="quit"/> Page 1 of 8

<button id="quit" constraints="borderlayout.south" text="quit"/> There is one frame element with two sub-elements for the two components. The elements have many more optional attributes, but these are the basics necessary to show something on screen. Next, you need a static main method for your application. HelloWorld.java public class HelloWorld { public JButton quit; public HelloWorld() throws Exception { new SwingEngine(this).render("HelloWorld.xml").setVisible(true); quit.addactionlistener(new ActionListener() { public void actionperformed(actionevent evt) { System.exit(0); ); public static void main(string [] args) throws Exception { new HelloWorld(); This class looks just like a normal Swing application. The only unusual thing is the following line: new SwingEngine(this).render("HelloWorld.xml").setVisible(true); This is what calls the SwiXml API to parse the HelloWorld.xml file and makes the resulting frame visible on screen. To compile and run the application code, you need to have the SwiXml and JDOM.jars in your classpath: javac -classpath swixml.jar:jdom.jar HelloWorld.java java -classpath swixml.jar:jdom.jar:. HelloWorld Running the program above will give you an application that looks like Figure 1: Figure 1. HelloWorld using SwiXml There is a lot of magic involved here, so I will go through it step by step. The SwingEngine class is a parser that reads and processes the XML file. It takes each element in the XML and converts it into a Swing component, placing them directly in the hierarchy. This is all pretty straightforward. The quit button is the tricky part. The button is declared as a field in the HelloWorld class, but the object is never directly created or assigned, and yet the addactionlistener method doesn't throw a NullPointerException. How can this happen? Page 2 of 8

If you look at the XML file closely, you will see the button element has an attribute called id with a value of quit. At run time, the SwingEngine will create the button object during the parsing phase and then assign it to the quit field using reflection. This means the quit field will no longer be null by the time the action listener is added. In order to perform this sleight of hand, the SwingEngine needs a reference to the class with the fields, in this case HelloWorld. That is why I passed this into the SwingEngine constructor. It is this reflection trick that makes SwiXml so powerful. With a reference to your main class, SwingEngine can build any user interface and attach it directly to your fields, saving you lots of boilerplate code. The reflection-based system also has the benefit of keeping your GUI layout separate from your event-handling logic, making maintenance a lot easier in the long run. Note that you may need to make your GUI component fields public so that SwiXml can access them. Recent versions of SwiXml can access any field, public, protected, or private; using reflection, however, accessing private fields may cause a security violation in sandbox environments like applets or unsigned Java Web Start applications. SwiXml can handle pretty much every Swing component, including menus, tables, and even inner frames. It uses a simple naming system (usually just dropping the leading "J") so if you already know Swing, it will be easy to learn. All of the standard layouts are supported, as well, though using the GridBagLayout from XML can be cumbersome (just as it is in code form). Let's take a look at another example that uses more complicated layout and some nested components. EmailTest.xml <?xml version="1.0" encoding="utf-8"?> <frame size="640,480" title="email Application" defaultcloseoperation="jframe.exit_on_close"> <menubar> <menu text="file"> <menuitem text="new"/> <menuitem text="send"/> <menuitem text="close"/> <separator/> <menuitem text="quit" id="quit"/> </menu> <menu text="edit"> <menuitem text="cut" accelerator="meta X"/> <menuitem text="copy" accelerator="meta C"/> <menuitem text="paste" accelerator="meta V"/> </menu> </menubar> <panel layout="borderlayout"> <hbox constraints="borderlayout.north"> <vbox> <label text="to :"/> <label text="subject :"/> </vbox> <vbox> <textfield Text="joshua.marinacci@sun.com"/> <textfield text="swixml is really cool!"/> </vbox> </hbox> <scrollpane constraints="borderlayout.center"> <textarea> </textarea> </scrollpane> </panel> This XML file is launched from code that looks like this: Page 3 of 8

EmailTest.java public class EmailTest { public JMenuItem quit; public EmailTest() throws Exception { new SwingEngine(this).render("EmailTest.xml").setVisible(true); quit.addactionlistener(new ActionListener() { public void actionperformed(actionevent evt) { System.exit(0); ); public static void main(string[] args) throws Exception { new EmailTest(); The finished layout looks like Figure 2: Figure 2. Email layout using SwiXml SwiXml and Actions In addition to components, SwiXml has direct support for Actions. You can bind a button, menu item, or any other Action-aware component directly to an Action field in your main class. It also lets you set Action properties like mnemonics, accelerators, and tooltips directly from your XML file. These features let you remove more code from your classes, resulting in a cleaner application design and more maintainable programs. Page 4 of 8

Here is a simple example showing an Action shared between two components. ActionTest.java public class ActionTest { // Create an Action as a member variable public Action quit = new AbstractAction() { public void actionperformed(actionevent evt) { System.exit(0); ; public ActionTest() throws Exception { // set the Action's name quit.putvalue(action.name, "Quit"); // build the GUI new SwingEngine(this).render("ActionTest.xml").setVisible(true); public static void main(string[] args) throws Exception { new ActionTest(); The code above creates an Action member variable called quit. Notice that the ActionTest constructor sets the NAME property of the action to "Quit" before building the GUI from XML. This ensures that any components which use the action will start with the same NAME property. If the property was set after building the GUI, then any customizations done by the XML would be overridden by the putvalue() call, which may not be the desired behavior. ActionTest.xml <frame size="200,200" title="action Test"> <menubar> <menu text="file"> <menuitem action="quit" accelerator="meta X"/> </menu> </menubar> <button action="quit" text="a Quit Button" ToolTipText="This is a quit button."/> The XML file above creates a frame with one button and one menu item. The two components share the same action by using action attributes that point to the same named action: quit. The menuitem has a second attribute, accelerator, which overrides the current accelerator property of the action, if any. The button element has extra attributes to set the text and tooltip text for the button. These settings will override the defaults in the action, allowing you to customize values for each component. If the properties are later set on the action using putvalue(), then the new value would override any values set here in the XML. By combining actions and the XML settings in different ways, you can create the appropriate behavior for your application. Page 5 of 8

Using XInclude As your interface grows, you may want to split the UI definition into multiple files. SwiXml supports this in two ways. First, you can use multiple files and load them independently. For example, you could create one file for your main application screen, one for the help system, and one for the preferences dialog. Any SwiXml file can be resolved into an instance of Component, so you can structure your files to build frames, panels, or even a single text field, each loaded with a call to SwingEngine.render(). SwiXml also supports the XInclude syntax, letting you split your XML into several files that are bound into one master file and loaded as a single unit. This can be used to separate sub-panels and menus into other files without effecting the Java code at all. Here is a simple example that has a main XML file (XITMain.xml) containing the main GUI and a secondary file (XITSub.xml) containing a sub-panel. XITMain.xml <frame size="320,150" title="xinclude Test"> <menubar> <menu text="file"> <menuitem text="open"/> <menuitem text="save"/> <menuitem text="close"/> <menuitem text="quit"/> </menu> </menubar> <panel constraints="borderlayout.center"> <button text="button in the main file."/> </panel> <panel constraints="borderlayout.south" include="xitsub.xml#subpanel"/> XITSub.xml <doc> <panel id="subpanel" layout="borderlayout"> <button text="button in an included file."/> </panel> </doc> XIncludeTest.java public class XIncludeTest { public XIncludeTest() throws Exception { new SwingEngine(this).render("XITMain.xml").setVisible(true); public static void main(string[] args) throws Exception { new XIncludeTest(); In the code above, the SwingEngine will combine the XITMain.xml and the XITSub.xml files at run time. The Java code doesn't even know that there are two files involved. It sees a unified component tree and can interact with it as normal. This transparent ability to merge multiple files gives the developer a powerful organizing tool that doesn't clutter up the Swing code at all. Page 6 of 8

Custom Components If there isn't a standard Swing class that does what you want, you are always free to build a custom component. SwiXml can support your custom component through a feature called custom tags. These let you define new tags that map to your components. For example, suppose I have a custom JButton subclass that I use over and over in a drawing program: ColorButton.java import java.awt.*; public class ColorButton extends JButton { public void paintcomponent(graphics g) { g.setcolor(getforeground()); g.fillrect(0,0,getwidth(),getheight()); g.setcolor(color.black); g.drawrect(0,0,getwidth()-1,getheight()-1); I can define a custom XML element called <colorbutton> by registering it in the SwingEngine's tag library like this: CustomComponentTest.java public class CustomComponentTest { public CustomComponentTest() throws Exception { SwingEngine eng = new SwingEngine(this); eng.gettaglib().registertag("colorbutton",colorbutton.class); eng.render("customcomponenttest.xml").setvisible(true); public static void main(string[] args) throws Exception { new CustomComponentTest(); Once the class is registered I can use it in my XML just like any other Swing component: CustomComponentTest.xml <frame size="320,200"> <colorbutton constraints="borderlayout.center" foreground="blue"/> <label constraints="borderlayout.south" text="color Test"/> Once compiled, the finished program would look like Figure 3: Figure 3. A Custom Component using SwiXml Page 7 of 8

Conclusion SwiXml has many features beyond what I have discussed here; these include direct support for resource bundles, making it very easy to localize your application. There are also built-in extensions for Mac OS X, like automatically using the single menu bar and binding actions to the Application menu. SwiXml is a powerful GUI layout tool, and most importantly, layout is the only thing it does. It doesn't have features to specify event code, animations, or anything else. This means it is easy to learn and small enough to use pretty much anywhere you can use Swing, even in downloaded Java Web Start applications or applets. Best of all, SwiXml is free and released under an Apache license. This author once created his own similar layout binding system and has now switched entirely to SwiXml because it does the job very well with little extra effort. The net result of working with SwiXml is delivering better-looking applications in less time, and that is always a good thing. Resources Sample code for this article SwiXml home page Joshua Marinacci first tried Java in 1995 at the request of his favorite TA and has never looked back. java.net RSS Feedback FAQ Press Terms of Participation Terms of Use Privacy Trademarks Site Map Your use of this web site or any of its content or software indicates your agreement to be bound by these Terms of Participation. Copyright 1995-2006 Sun Microsystems, Inc. Powered by Sun Microsystems, Inc., O'Reilly and CollabNet Page 8 of 8