Electrical and Computer Engineering Object-Oriented Topic : User Interface Components with Swing GUI Part III Maj Joel Young Joel.Young@afit.edu 17-Sep-03 Maj Joel Young
Creating GUI Apps The Process Overview Step 1. Create a JFrame Step 2. Create JPanel(s) to hold controls Step 3. Add JPanel(s) to JFrame s content pane, and put JPanels within other JPanels as needed Step 4. Create Controls Step 5. Add Controls to JPanel(s) Step 6. Create event listeners, add to components Title Here Label: Ok Text Field Cancel // The Listener class MyActionListener implements ActionListener public void actionperformed( ActionEvent e) JOptionPane.showMessageDialog( null, "Button clicked!"); 2
Layout Managers - Basics Positioning controls/panels is not a trivial task What if the user resizes the window? What if the resolution of the screen is changed? What if the application is run on two different operating system environments? (Win 2000, Solaris) Layout Managers help to keep our interfaces organized even if the above changes do occur A layout manager sets the policy for how an interface s components will be ordered, stacked, and packed 3
Layout Managers - Basics There are many kinds of layout managers: Border Layout (simple): Organizes display into North, South, East, West, and Center regions Flow Layout (simple): Organizes display by simply creating rows of components, where a new row is created when horizontal space runs out Grid Layout (medium): Organizes display into an evenly divided grid, where each component gets one cell Box Layout (medium): Organizes display into a column or row of boxes, the size of which can be specified Gridbag Layout (complex): Organizes display into a grid, but components may take multiple cells, and cells are not of uniform size Null Layout: No layout management, components are placed at specific X,Y coordinates and never move or resize 4
Border Layout public class TestFrame5 extends JFrame public TestFrame5() // Create a JPanel with a border layout JPanel p = new JPanel(new BorderLayout()); // Add labels p.add(new JButton("North"),BorderLayout.NORTH); p.add(new JButton("South"),BorderLayout.SOUTH); p.add(new JButton("East"),BorderLayout.EAST); p.add(new JButton("West"),BorderLayout.WEST); p.add(new JButton("Center"),BorderLayout.CENTER); // Add panel to content pane this.getcontentpane().add(p); TestFrame5 testframe = new TestFrame5(); testframe.setsize(300,300); testframe.show(); 5
FlowLayout public class TestFrame6 extends JFrame public TestFrame6() // Create a JPanel with a flow layout - centering items JPanel p = new JPanel(new FlowLayout(FlowLayout.CENTER)); // Add labels p.add(new JButton("First")); p.add(new JButton("Second")); p.add(new JButton("Third")); p.add(new JButton("Fourth")); p.add(new JButton("Fifth")); // Add panel to content pane this.getcontentpane().add(p); TestFrame6 testframe = new TestFrame6(); testframe.setsize(300,300); testframe.show(); 6
Grid Layout public class TestFrame7 extends JFrame public TestFrame7() // Create a JPanel with a grid layout JPanel p = new JPanel(new GridLayout(3,2)); // Add labels p.add(new JButton("Row 1, Col 1")); p.add(new JButton("Row 1, Col 2")); p.add(new JButton("Row 2, Col 1")); p.add(new JButton("Row 2, Col 2")); p.add(new JButton("Row 3, Col 1")); // Add panel to content pane this.getcontentpane().add(p); TestFrame7 testframe = new TestFrame7(); testframe.setsize(300,300); testframe.show(); 7
Buttons Plain Vanilla Buttons (JButton) Clicking causes an action to occur (fires ActionEvent) Can have a text label, icon, or both Checkbox Buttons (JCheckBox) A toggle button click to turn on state Application can examine to see if button selected or not Radio Buttons (JRadioButton) A toggle button but buttons are arranged in groups, and only one button can be active Application can examine which is active 8
Button Example public class ButtonTest1 extends JFrame public ButtonTest1() // Create a JPanel with a box layout JPanel p = new JPanel(); p.setlayout(new BoxLayout(p,BoxLayout.Y_AXIS)); // Add buttons JButton tb = new JButton("Text Button"); tb.setalignmentx(component.center_alignment); p.add(tb); JButton ib = new JButton(new ImageIcon("icons/Help24.gif")); ib.setalignmentx(component.center_alignment); p.add(ib); this.getcontentpane().add(p); ButtonTest1 testframe = new ButtonTest1(); testframe.setsize(300,300); testframe.show(); 9
CheckBox Button Example public class ButtonTest2 extends JFrame implements ActionListener JCheckBox cbred = new JCheckBox("Red"); JCheckBox cbgreen = new JCheckBox("Green"); JCheckBox cbblue = new JCheckBox("Blue"); JLabel sellabel = new JLabel("Selected: (none)"); public ButtonTest2() // Create a JPanel with a box layout JPanel p = new JPanel(); p.setlayout( new BoxLayout(p,BoxLayout.Y_AXIS)); // Add buttons cbred.addactionlistener(this); p.add(cbred); cbgreen.addactionlistener(this); p.add(cbgreen); cbblue.addactionlistener(this); p.add(cbblue); p.add(box.createrigidarea( new Dimension(0,20))); p.add(sellabel); // Add panel to content pane this.getcontentpane().add(p); public void actionperformed(actionevent e) String label = "Selected: "; if (cbred.isselected()) label += "Red "; if (cbgreen.isselected()) label += "Green "; if (cbblue.isselected()) label += "Blue"; sellabel.settext(label); ButtonTest2 testframe = new ButtonTest2(); testframe.setsize(300,300); testframe.show(); 10
Labels (JLabel) Usually displays a line of text to explain something on the display (like a prompt next to a text field) Can also be an image, or an image with text Label does not get keyboard focus, does not issue labelspecific events Can be dynamically changed by the application (useful for counters or status fields) 11
Label Example public class LabelTest1 extends JFrame public LabelTest1() // Create a JPanel with a box layout JPanel p = new JPanel(); p.setlayout(new BoxLayout(p,BoxLayout.X_AXIS)); // Add controls p.add(box.createhorizontalglue()); JLabel lb = new JLabel("Click this button to explode:"); lb.setalignmenty(component.center_alignment); p.add(lb); p.add(box.createrigidarea(new Dimension(5,0))); JButton tb = new JButton("Self-Destruct"); tb.setalignmenty(component.center_alignment); p.add(tb); p.add(box.createhorizontalglue()); // Add panel to content pane this.getcontentpane().add(p); LabelTest1 testframe = new LabelTest1(); testframe.setsize(300,300); testframe.show(); 12
Dynamic Label Example public class LabelTest1 extends JFrame int counter = 0; JLabel hitlabel; public LabelTest1() // Create a JPanel with a box layout JPanel p1 = new JPanel(); p1.setlayout(new BoxLayout(p1,BoxLayout.X_AXIS)); // Add controls p1.add(box.createhorizontalglue()); JLabel lb = new JLabel("Click this button to explode:"); lb.setalignmenty(component.center_alignment); p1.add(lb); p1.add(box.createrigidarea(new Dimension(5,0))); JButton tb = new JButton("Self-Destruct"); tb.setalignmenty(component.center_alignment); tb.addactionlistener(new ActionListener() public void actionperformed(actionevent e) hitlabel.settext(string.valueof(++counter)); ); p1.add(tb); p1.add(box.createhorizontalglue()); JPanel p2 = new JPanel(); p2.setlayout(new FlowLayout(FlowLayout.CENTER)); hitlabel = new JLabel(""); p2.add(hitlabel); LabelTest1 testframe = new LabelTest1(); testframe.setsize(300,300); testframe.show(); // Add panel to content pane this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p1,borderlayout.center); this.getcontentpane().add(p2,borderlayout.south); 13
Text Handling Text Fields (JTextField) Used to input small amounts of text (usually single fields, like names or addresses) Text Editors (JTextEditor, JTextPane) Essentially small word processors that can be embedded in your GUI Text Areas (JTextArea) Simplified text editing controls 14
Text Field Example public class TextFieldTest1 extends JFrame JTextField usertext; public TextFieldTest1() // Create a JPanel with a box layout JPanel p1 = new JPanel(); p1.setlayout(new BoxLayout(p1,BoxLayout.X_AXIS)); // Create a label for a prompt JLabel prompt = new JLabel("Enter Name:"); p1.add(prompt); // Create text field usertext = new JTextField(); usertext.setmaximumsize(new Dimension(150,20)); usertext.addactionlistener(new ActionListener() public void actionperformed(actionevent e) JOptionPane.showMessageDialog(null, "You typed:"+usertext.gettext()); ); p1.add(usertext); this.getcontentpane().add(p1); TextFieldTest1 testframe = new TextFieldTest1(); testframe.setsize(300,300); testframe.show(); 15
JTextPane/JTextEditor Example public class TextFieldTest2 extends JFrame JTextPane tp = new JTextPane(); JEditorPane ep = new JEditorPane("text/html",""); public TextFieldTest2() // Create a JPanel with a box layout JPanel p1 = new JPanel(); p1.setlayout(new GridLayout(1,2)); // Create a ScrollPane for the TextPane JScrollPane sp = new JScrollPane(tp); p1.add(sp); sp = new JScrollPane(ep); p1.add(sp); ep.seteditable(false); // Add a button to transfer text JPanel p2 = new JPanel( new FlowLayout(FlowLayout.CENTER)); JButton copy = new JButton("Copy"); copy.addactionlistener(new ActionListener() public void actionperformed(actionevent e) ep.settext(tp.gettext()); ); p2.add(copy); this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p1,borderlayout.center); this.getcontentpane().add(p2,borderlayout.south); TextFieldTest2 testframe = new TextFieldTest2(); testframe.pack(); testframe.show(); 16
Borders All JComponents allow you to specify a border Types of Borders Line borders Etched borders Beveled borders Title borders www.java.sun.com/tutorial 17
JTextPane/JTextEditor Example public class TextFieldTest2 extends JFrame JTextPane tp = new JTextPane(); JEditorPane ep = new JEditorPane("text/html",""); public TextFieldTest2() // Create Borders Border etch = BorderFactory.createEtchedBorder(); // Create a JPanel with a box layout JPanel p1 = new JPanel(); p1.setlayout(new GridLayout(1,2)); // Create a ScrollPane for the TextPane JScrollPane sp = new JScrollPane(tp); sp.setborder( BorderFactory.createTitledBorder(etch,"Text Pane")); p1.add(sp); sp = new JScrollPane(ep); sp.setborder( BorderFactory.createTitledBorder(etch,"Editor Pane")); p1.add(sp); ep.seteditable(false); // Add a button to transfer text JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER)); JButton copy = new JButton("Copy"); copy.addactionlistener(new ActionListener() public void actionperformed(actionevent e) ep.settext(tp.gettext()); ); p2.setborder(etch); p2.add(copy); this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p1,borderlayout.center); this.getcontentpane().add(p2,borderlayout.south); TextFieldTest2 testframe = new TextFieldTest2(); testframe.pack(); testframe.show(); 18
Lists Plain Lists (JList) Just show a list of items Single or multiple select Scrollable Drop-Down Lists (JComboBox) Show a list of options you can pick from Can t be altered by user Combo Lists (JComboBox) Same as drop-down, but allows users to edit entries 19
JList Example public class TestList1 extends JFrame implements ActionListener private JList list; private DefaultListModel model; private JTextField text; public TestList1() // Create model, populate with data model = new DefaultListModel(); model.addelement("csce 694"); model.addelement("csce 646"); model.addelement("csce 593"); model.addelement("eeng 653"); // Create list, specify data model list = new JList(model); JScrollPane sp = new JScrollPane(list); // Create a JPanel with a box layout JPanel p = new JPanel(); p.setlayout(new BoxLayout(p,BoxLayout.X_AXIS)); text = new JTextField(); text.setminimumsize(new Dimension(150,5)); p.add(text); JButton b = new JButton("Add Class"); b.addactionlistener(this); p.add(b); // Add panel to content pane this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p,borderlayout.south); this.getcontentpane().add(sp,borderlayout.center); public void actionperformed(actionevent e) model.addelement(text.gettext()); text.settext(""); TestList1 testframe = new TestList1(); testframe.setsize(300,300); testframe.show(); 20
JList Example with Selection Listener public class TestList2 extends JFrame implements ListSelectionListener private JList list; private DefaultListModel model; private JLabel text; public TestList2() // Create model, populate with data model = new DefaultListModel(); model.addelement("csce 694"); model.addelement("csce 646"); model.addelement("csce 593"); model.addelement("eeng 653"); // Create list, specify data model list = new JList(model); list.addlistselectionlistener(this); JScrollPane sp = new JScrollPane(list); // Create a JPanel with a flow layout JPanel p = new JPanel(new FlowLayout()); text = new JLabel("(Nothing selected)"); p.add(text); public void valuechanged(listselectionevent e) String item = (String) list.getselectedvalue(); text.settext(item); TestList2 testframe = new TestList2(); testframe.setsize(300,300); testframe.show(); // Add panel to content pane this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p,borderlayout.south); this.getcontentpane().add(sp,borderlayout.center); 21
JComboBox Example Not Editable public class TestList3 extends JFrame implements ActionListener private JComboBox list; private JLabel text; public TestList3() text = new JLabel("(Nothing selected)"); // Create combo box list = new JComboBox(); list.additem("csce431"); list.additem("csce492"); list.additem("csce486"); list.additem("csce531"); list.additem("csce586"); list.additem("csce593"); list.additem("csce646"); // Scroll after four entries list.setmaximumrowcount(4); // Respond to selections list.addactionlistener(this); // Create a JPanel with a flow layout JPanel p = new JPanel(new FlowLayout()); p.add(text); public void actionperformed(actionevent e) String item = (String) list.getselecteditem(); text.settext("registered for: "+item); TestList3 testframe = new TestList3(); testframe.setsize(300,300); testframe.show(); // Add panel to content pane this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p,borderlayout.south); this.getcontentpane().add(new JLabel(" "),BorderLayout.CENTER); this.getcontentpane().add(list,borderlayout.north); 22
JComboBox Example -- Editable public class TestList4 extends JFrame implements ActionListener private JComboBox list; private JLabel text; public TestList4() text = new JLabel("(Nothing selected)"); // Create combo box list = new JComboBox(); list.additem("csce431"); list.additem("csce492"); list.additem("csce486"); list.additem("csce531"); list.additem("csce586"); list.additem("csce593"); list.additem("csce646"); // Make editable list.seteditable(true); // Scroll after four entries list.setmaximumrowcount(4); // Respond to selections list.addactionlistener(this); // Create a JPanel with a flow layout JPanel p = new JPanel(new FlowLayout()); p.add(text); // Add panel to content pane this.getcontentpane().setlayout(new BorderLayout()); this.getcontentpane().add(p,borderlayout.south); this.getcontentpane().add(new JLabel(" "),BorderLayout.CENTER); this.getcontentpane().add(list,borderlayout.north); public void actionperformed(actionevent e) String item = (String) list.getselecteditem(); text.settext("registered for: "+item); TestList4 testframe = new TestList4(); testframe.setsize(300,300); testframe.show(); 23
Menus Menus (JMenu) Top-level menu items, do not cause action to occur Containers for JMenuItems and other JMenus Menu Items (JMenuItem) Bottom-level menu items, selecting causes an action Menu Bars (JMenuBar) Container for menus, are placed in the JFrame 24
Menu Example // Modified example from The Java Tutorial public class TestMenu1 extends JFrame implements ActionListener JTextArea output; public TestMenu1() JMenuBar menubar; JMenu menu, submenu; JMenuItem menuitem; JRadioButtonMenuItem rbmenuitem; JCheckBoxMenuItem cbmenuitem; //Add regular components to the window Container contentpane = getcontentpane(); output = new JTextArea(5, 30); output.seteditable(false); contentpane.add(new JScrollPane(output), BorderLayout.CENTER); //Create the menu bar. menubar = new JMenuBar(); setjmenubar(menubar); //Build the first menu. menu = new JMenu("A Menu"); menubar.add(menu); //a group of JMenuItems menuitem = new JMenuItem("A menu item", KeyEvent.VK_T); menuitem.addactionlistener(this); menu.add(menuitem); menuitem = new JMenuItem("Another menu item",keyevent.vk_b); menuitem.addactionlistener(this); menu.add(menuitem); 25
Menu Example -- Continued //a group of radio button menu items menu.addseparator(); ButtonGroup group = new ButtonGroup(); rbmenuitem = new JRadioButtonMenuItem( "A radio button menu item"); rbmenuitem.setselected(true); group.add(rbmenuitem); rbmenuitem.addactionlistener(this); menu.add(rbmenuitem); rbmenuitem = new JRadioButtonMenuItem( "Another one"); group.add(rbmenuitem); rbmenuitem.addactionlistener(this); menu.add(rbmenuitem); //a group of check box menu items menu.addseparator(); cbmenuitem = new JCheckBoxMenuItem( "A check box menu item"); cbmenuitem.addactionlistener(this); menu.add(cbmenuitem); cbmenuitem = new JCheckBoxMenuItem( "Another one"); cbmenuitem.addactionlistener(this); menu.add(cbmenuitem); //a submenu menu.addseparator(); submenu = new JMenu("A submenu"); menuitem = new JMenuItem( "An item in the submenu"); menuitem.addactionlistener(this); submenu.add(menuitem); menuitem = new JMenuItem("Another item"); menuitem.addactionlistener(this); submenu.add(menuitem); menu.add(submenu); //Build second menu in the menu bar. menu = new JMenu("Another Menu"); menubar.add(menu); public void actionperformed(actionevent e) JMenuItem source = (JMenuItem)(e.getSource()); String s = "Item clicked: "+source.gettext()+"\n"; output.append(s); TestMenu1 window = new TestMenu1(); window.setsize(450, 260); window.setvisible(true); 26
Approach to building a user interface the interface (pen and paper, or visual toolkit) Convert design to code Make the components in the interface look the way you want them to Position user interface components where you want them Handle user input (respond to events generated by user interface components) In Java Create the component with the appropriate constructor parameters Add a flow layout manager to container Add individual components to container Add appropriate event handlers (listener interfaces) 27
Homework Code the basic GUI window for your tabulation mode display, buttons, operations, =, clear No functionality required, not even for number buttons to cause text to appear in the display REMEMBER! Draw it on paper. Use containers to group things (maybe a grid for the numbers beside a grid for the operations, with a display on top). Amazed at how easy it is? 28