The Java Series: The Java Series. GUI Building With Swing Raul RAMOS / CERN-IT User Support Slide 1
The Java Series: The Java Series. GUI Building With Swing Raul RAMOS / CERN-IT User Support Slide 1
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 1
What is JFC?
The Java Foundation Classes (JFC) are a comprehensive set of GUI components and services to simplify the development and deployment of commercial-quality desktop applications. Its an effort to provide a complete CLASS LIBRARY to build modern GUIs out-of-the-box. With JFC youll get most of what you need when developing any kind of user interface.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 2
Whats in JFC
Swing: A complete set of graphical components Pluggable look & feel. Java 2D: To render, manipulate and transform, complex 2D images and text. Drag & Drop programmability. Accessibility. SWING IS FOR GUI BUILDING
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 3
Provides the basic functionality for GUI building. Provides a minimum set of components. Complex GUI require complex applications. Components difficult to customize extend. JFC extends AWT JFC provides more components and more functionality. AWT provides: The Event Model. The Component/Container conceptualization.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 4
SWING GUI classes Model/View arch. Pluggable Look&Feel Accessibility Java 2D Drag&Drop
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 5
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 6
This Talk
We are going to see how to use and customize Swing components. Two ways to use Swing (two parts of the lecture): A high level set of graphical components ready to use. Easy to use in your programs. An architecture upon which to build and customize components to any degree. Very flexible. The Event Model is the one from AWT so we are going to use it in the exact same way as in AWT.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 7
import java.awt.*; public class MyApplication { public static void main (String[] args) { Choice l = new Choice(); l.addItem("Item 1"); A few components. Each l.addItem("Item 2"); component has its own l.addItem("Item 3"); methods, constructors, etc..
specific to the function they perform.
TextArea ta = new TextArea(5,20); TextField tf = new TextField(); Label lb = new Label("This is an example"); Frame f = new Frame("Some sample"); f.setLayout(new GridLayout(2,2)); f.setLocation(100,100); f.add (lb, new Dimension(1,1)); f.add (l, new Dimension(1,2)); f.add (tf, new Dimension(2,1)); f.add (ta, new Dimension(2,2)); f.pack(); f.show(); } }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 9
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
import java.awt.event.*; public class MyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("A button has been pressed"); } }
import java.awt.*; public class MyApplication { public static void main (String[] args) { Button b = new Button ("Press me"); MyActionListener alistener = new MyActionListener(); b.addActionListener(alistener); Frame f = new Frame("Some sample"); f.setLayout(new FlowLayout()); f.setLocation(100,100); f.add (b); f.pack(); f.show(); } }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 11
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 12
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 13
Using Swing
If you have jdk 1.2: it comes with it you dont have to do anything. Otherwise:
download swing for jdk 1.1 from:
http://java.sun.com/products/jfc/download.html
Scenario 1
Create some components
public static void main (String args[]) { // Create the frame JFrame frame = new JFrame ("My Application"); // Create some components JButton b1 = new JButton("A Button"); b1.setToolTipText("This is the left button"); JButton b2 = new JButton(new ImageIcon("middle.gif")); b2.setToolTipText("This is the middle button"); JLabel label = new JLabel(new ImageIcon("alb.gif"));
JTextField text = new JTextField(20); Vector items = new Vector(); for (int i=1; i<20; i++) { items.addElement("This is item "+i); } JList list = new JList(items); list.setToolTipText("Select one item"); JScrollPane listPane = new JScrollPane(list); //Lay out the content pane. Create a JPanel JPanel contentPane = new JPanel(); contentPane.setLayout(new FlowLayout()); contentPane.setPreferredSize(new Dimension(300, 300)); contentPane.add(b1); contentPane.add(b2); Set a Layout Manager contentPane.add(label); contentPane.add(text); contentPane.add(listPane); frame.setContentPane(contentPane); Add to the JPanel frame.pack(); frame.show(); Associate the JPanel to the Frame
} }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 16
Scenario 1.2
We extend JPanel
public class FirstSample extends JPanel { public FirstSample() { Use the constructor to add components super(); // Create some components JButton b1 = new JButton("A Button"); .. .. .. add(label); add(text); add(listPane);
} public static void main (String args[]) { JFrame frame = new JFrame("First Sample"); frame.setContentPane(new FirstSample()); frame.pack(); frame.show(); JFrame frame2 = new JFrame("Another First Sample"); frame2.setContentPane(new FirstSample()); frame2.pack(); frame2.show(); } }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 18
Interesting JComponents
JButton, JList, JLabel, JTextXXX, JComboBox, JRadioButton, JCheckBox extend functionality existing in AWT Components. JProgressBar, JSlider, JTable, JToolBar, JTree provide new components. JInternalFrame, JScrollPane, JSplitPane, JTabbedPane provide new ways to combine components. See the doc:
wwwinfo.cern.ch/support/java/docs/api The Java Tutorial: wwwinfo.cern.ch/support/java/docs
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 19
Scenario 2: JToolBar
Same technique as before import java.util.*; import javax.swing.*; import java.awt.*; public class ToolBarSample extends JPanel { public ToolBarSample () { super(); Create a JToolBar // Create a toolbar JToolBar mybar = new JToolBar(); mybar.add(new JButton(new ImageIcon("open.gif"))); mybar.add(new JButton(new ImageIcon("save.gif"))); object
JButton cut = new JButton(new ImageIcon("cut.gif")); cut.setToolTipText("Cut Selection"); JButton copy = new JButton(new ImageIcon("copy.gif")); copy.setToolTipText("Copy Selection"); mybar.add(cut); mybar.add(copy); // Create some components .. .. .. add("North", mybar); add("South", label); add("Center", text); } public static void main (String args[]) { // Create the frame and the content JFrame frame = new JFrame ("My Application"); ToolBarSample tb = new ToolBarSample(); frame.setContentPane(tb); frame.pack(); frame.show(); } }
Add buttons to it
And ready to go
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 20
JScrollPane
A generic container to put anything youd like to be scrollable: Images, Data, Text, You can put any component in an JScrollPane and Swing will take care of everything. The Component inside the JScrollPane must be Scrollable (interface). Most of Swing components are Scrollable See next scenario with and without the ScrollPane
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 21
Scenario 3: Scrolling
import java.util.*; import javax.swing.*; import java.awt.*; Create the component public class ScrollSample extends JPanel { Put into a JScrollPane public ScrollSample() { JTextArea text = new JTextArea(); JScrollPane textPane = new JScrollPane(text); //Lay out the pane. setLayout(new BorderLayout()); setPreferredSize(new Dimension(300, 300)); add("Center", textPane); } public static void main (String args[]) { // Create the frame JFrame frame = new JFrame ("My Application"); ScrollSample scroll = new ScrollSample(); frame.setContentPane(scroll); frame.pack(); frame.show(); } }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
JTable
A Table is a grid of cells. The JTable class provides the basic functionality. The data in the table is separated from the JTable object itself. To create a table: Instantiate a JTable object Create a class to hold the data Instantiante a data object Associate the Table object with the data object The Data class must be derived from AbstractTableModel Then you can use generic and specific Listeners as in any other component
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 23
Scenario 4: Tables
import import import import java.util.*; javax.swing.*; javax.swing.table.*; java.awt.*;
class MyTableModel extends AbstractTableModel { public int getColumnCount() { return 10; } public int getRowCount() { return 10;} public Object getValueAt(int row, int col) { return new Integer(row*col); } } public class TableSample extends JPanel { public TableSample() { super();
MyTableModel dataModel = new MyTableModel(); JTable table = new JTable(dataModel); table.setPreferredScrollableViewportSize (new Dimension(300, 100)); JScrollPane scrollpane = new JScrollPane(table); //Lay out the content pane. setLayout(new FlowLayout()); add(scrollpane);
} public static void main (String args[]) { // Create the frame JFrame frame = new JFrame ("Table Sample"); frame.setContentPane(new TableSample()); frame.pack(); frame.show(); } }
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 24
JTree
The principles are the same as JTable Create your data + Associate with tree. A tree is made of nodes. Tree data is created through the DefaultMutableTreeNode class. We need to: Define one root node. Add nodes to each other to build the tree structure.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 25
public class TreeSample extends JPanel { public TreeSample() { Create the root node super(); // Create the tree structure DefaultMutableTreeNode top = new DefaultMutableTreeNode("The root of all"); DefaultMutableTreeNode primo = new DefaultMutableTreeNode ("The First Node"); top.add(primo); primo.add(new DefaultMutableTreeNode ("The firs .. .. primo.add(new DefaultMutableTreeNode ("The second .. DefaultMutableTreeNode second = new DefaultMutableTreeNode ("The Second Node"); top.add(second); second.add(new DefaultMutableTreeNode ("The first .. second.add(new DefaultMutableTreeNode ("The second ..
Scenario 5: Trees
new DefaultMutableTreeNode ("Category"); second.add(category); category.add(new DefaultMutableTreeNode("Bussines")); category.add(new DefaultMutableTreeNode ("Science")); JTree tree = new JTree(top); JScrollPane scrollpane = new JScrollPane(tree); //Lay out the content pane. setLayout(new BorderLayout()); setPreferredSize(new Dimension(350,300)); add("Center", scrollpane); } } .. .. .. The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
JSplitPanel
To share the same physical space simultaneously between two containers
To use it: Create the two components Create a JSplitPanel Insert them into the JSplitPanel
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 27
JSplitPane pane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); TreeSample tree = new TreeSample(); ScrollSample text = new ScrollSample(); pane.setLeftComponent(tree); pane.setRightComponent(text); pane.setDividerLocation(150); pane.setDividerSize(10);
//Lay out the content pane. setPreferredSize(new Dimension(350, 300)); setLayout(new GridLayout(1,1)); add(pane, new Dimension(1,1)); } } .. .. .. The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 28
JTabPanel
To share the same physical space between any number of components The principles like the SplitPanel. Create objects + add them.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 29
JTabbedPane tpane = new JTabbedPane(); tpane.addTab("ScrollSample", new ImageIcon("open.gif"), new ScrollSample(), "The Previous Scroll Sample"); tpane.addTab("SplitSample", null, new SplitSample(), null); tpane.addTab("TreeSample", new ImageIcon("save.gif"), new TreeSample(), "The Tree Sample"); tpane.addTab("TableSample", null, new TableSample(), "The Table Sample"); //Add the tabbed pane to this panel. setLayout(new GridLayout(1, 1)); add(tpane); } .. .. .. }
Create and add other components. We are using our previous examples. Can specify infos when adding
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 30
Internal Frame
A desktop within a window:
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 31
Scenario 8: Desktops
import javax.swing.*; import java.awt.*; import java.awt.event.*;
Extend JFrame
public class InternalFrameSample extends JFrame implements ActionListener{ JDesktopPane desktop; JButton b1, b2, b3, b4, b5; int offsetx=50; int offsety=50; public InternalFrameSample() { super("Internal Frame Demo"); desktop = new JDesktopPane(); JToolBar toolbar = new JToolBar(); b1 = new JButton ("Scroll Sample"); b2 = new JButton ("Split Sample"); b3 = new JButton ("Tree Sample"); b4 = new JButton ("Table Sample"); b5 = new JButton ("Tabs Sample"); toolbar.add(b1); toolbar.add(b2); toolbar.add(b3); toolbar.add(b4); toolbar.add(b5); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this);
//Add the desktop pane to this panel. desktop.setLayout(new BorderLayout()); desktop.add("North", toolbar); setContentPane(desktop); }
public static void main (String args[]) { InternalFrameSample frame = new InternalFrameSample(); frame.pack(); frame.show(); }
public void actionPerformed (ActionEvent e) { JInternalFrame frame; if (e.getSource() == b1) { createInternalFrame("Scroll", new ScrollSample()); } else if (e.getSource() == b2) { createInternalFrame("Split", new SplitSample()); } else if (e.getSource() == b3) { createInternalFrame("Tree", new TreeSample()); } else if (e.getSource() == b4) { createInternalFrame("Table", new TableSample()); } else if (e.getSource() == b5) { createInternalFrame("Tab", new TabbedSample()); } }
InternalFrameSample objects are also ActionListeners (for the toolbar buttons in this case)
Slide 32
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Customizable Swing
Swing is a huge library. Behind every component there is a set of objects working to achieve its mission. This implies having a big amount of classes, interfaces, etc interrelated. See the doc: wwwinfo/support/java/docs/api
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 34
For every component AWT provides two objects: A Logical Object: Containing the high level properties and behaviors (data + painting) A Peer Object: Containing the low level interface with the platform. Final drawing and behavior is delegated to the platform.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 35
Swing Architecture
The implementation of every component is separated into: The Model of the component: containing the data, status... The View of the component: containing the graphics and event handling. This way we separate the data from the UI. For every component 4 objects: 2 implementing the model 2 implementing the view When we want to change something we change the relevant object. In AWT everything is in one object.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 36
Swing Architecture
Model Object: data + status. Notifies ChangeList. ChangeListener: what to do when model changes Notifies component about changes. Component Object: graphical properties. Gets data from model. Asks UI to repaint. UI Object: Final physical drawing (not the OS)
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support Slide 37
Swing Architecture
Remember the table: We created our own TableModel containing the data. We created a component object and associated to it. There are default implementations of these objects for each component. Depending on what we change we customize: The model object: Changes the data The changeListener object: Changes when the UI is updated after a change on the model. The Component object: Changes physical properties (position, size, contained components .) The UI object: Changes the look and feel.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 38
Swing Architecture
See the doc: JComponent.getUIClassID() JTable (introduction) JTable constructors JTable.createDefaultDataModel() JTable.createDefaultRenderers() JTable.getCellRenderer() JTable.getCellEditor() JTable.getUI() swing.plaf.* Observe: Complete independence of functionalities. Complete customizability. Complete modularity.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 39
Slide 40
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 41
Scenario 9: L&F
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 42
Scenario 9: L&F
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 43
Scenario 9
public class InternalFrameDemo extends JFrame { .. .. .. public void actionPerformed (ActionEvent e) { } else if (e.getSource() == b6) { changeLF(1); } else if (e.getSource() == b7) { When clicking a button changeLF(2); } else if (e.getSource() == b8) { changeLF(3); } } public void changeLF(int what) { String lf =""; if (what==1) { lf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";} else if (what==2) { lf = "javax.swing.plaf.metal.MetalLookAndFeel";} else if (what==3) { lf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; } try { UIManager.setLookAndFeel(lf); SwingUtilities.updateComponentTreeUI(this); } catch(Exception e) { e.printStackTrace(); } }
Slide 44
Summary
Swing extends AWT New components: Lightweight components JButton, JTree, Containers Split, Tabbed, Desktop Customizability through separation: Model part (data + status) View part (behavior + UI)
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 45
Swing
Free. Is now part of JDK 1.2. When established will be homogenous. In JDK 1.1.x is a separate library.
Modularization implies overhead (slow performance for heavy UIs) Recommendation: Swing out-of-the-box is enough for most of the needs. Learn model/view of the particular component you want to customize.
The Java Series. GUI Building with Swing Raul RAMOS / CERN-IT User Support
Slide 46