Handout 12 CS603 Object-Oriented Programming Fall 15 Page 1 of 12 Handout 14 Graphical User Interface (GUI) with Swing, Event Handling The Swing library (javax.swing.*) Contains classes that implement User Interface components Buttons, radio buttons, text fields, etc Extends an earlier library: AWT Dimension Font LayoutManager 1 Classes in the java.awt package Heavyweight FontMetrics Object Color Panel Applet JApplet Graphics Component Container Window Frame JFrame * Dialog JDialog JComponent Swing Components in the javax.swing package JComponent and its subclasses: AbstractButton JMenuItem JButton JCheckBoxMenuItem JMenu JRadioButtonMenuItem JToggleButton JCheckBox JComponent JEditorPane JRadioButton JTextComponent JTextField JPasswordField JTextArea JLabel JList JComboBox JPanel JOptionPane JScrollBar JSlider JTabbedPane JSplitPane JLayeredPane JSeparator JScrollPane JRootPane JToolBar JMenuBar JPopupMenu JFileChooser JColorChooser JToolTip JTree JTable JTableHeader - 1 - JInternalFrame JProgressBar JSpinner
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 2 of 12 Need a Container object in which to place UI components - will use JFrame. JFrame a window that cannot be put inside another window components can be added to a frame s content pane (getcontentpane() instance method) using method add First, a simple example: Create a window with a Label, TextField and 2 buttons, Hi and Exit. /** * Simple Java program displaying a window. */ import java.awt.container; import java.awt.flowlayout; import javax.swing.*; public class SimpleFrame extends JFrame { private JButton hi = new JButton("Hi"); private JButton exit = new JButton("Exit"); private JTextField tf = new JTextField(10); public SimpleFrame (){ // recall, the no arg constructor of superclas, // i.e. JFrame gets called here. this.setsize(450, 100); this.settitle("simple Frame example"); this.setlocation(300, 300); this.setdefaultcloseoperation(exit_on_close); // tell it how to lay out components this.setlayout(new FlowLayout()); // add components this.add(new JLabel("Enter your name")); this.add(tf); this.add(hi); this.add(exit); this.setvisible(true); public static void main(string[] args) { // instantiate the class, will display a window new SimpleFrame(); Common pitfalls: Don t forget to set a layout Don t forget to make the frame visible Otherwise the window will not show all components or may not show at all! - 2 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 3 of 12 Examples: some things that are commonly done: JLabel: JLabel l = new JLabel( Put text here ); l.settext( Change it here ); JTextFields: JTextField t1 = new JTextField(25); JTextField t2 = new JTextField( Balance, 20); t1.settext( Deposit ); // set content String s = t2.gettext(); // retrieve content t1.seteditable(false); // user can t change contents JTextArea: JTextArea a1 = new JTextArea(10, 25); // rows, cols JTextArea a2 = new JTextArea( list accounts:, 10, 25); a1.settext( account 1 ); // replace content a1.append( account 2 ); // append to content a2.append( account 1 ); // append to content a1.seteditable(false); // user can t change contents JList: Object [] oarray = ; JList l = new JList(oArray); Object o = l. getselectedvalue(); JRadioButton and ButtonGroups: JRadioButton add = new JRadioButton("Addition", true); JRadioButton subtract=new JRadioButton("Subtraction", false); The isselected() method returns true if the RadioButton is selected, and false otherwise. Add a component of type ButtonGroup to ensure to groups radio buttons so only 1 can be selected at any given time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); A Visual Guide to Swing Components: http://drootr.com/apcs/tutorial/ui/features/components.html - 3 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 4 of 12 Event Handling An event can be defined as a type of signal to the program that something has happened. The event is generated by external user actions such as mouse movements, mouse clicks, and keystrokes, or by the operating system, e.g. a timer event. Source Event Type User Action Object Generated Click a button JButton ActionEvent Click a check box JCheckBox ItemEvent, ActionEvent Click a radio button JRadioButton ItemEvent, ActionEvent Press return on a text field JTextField ActionEvent Select a new item JComboBox ItemEvent, ActionEvent Window opened, closed, etc. Window WindowEvent Mouse pressed, released, etc. Component MouseEvent Mouse moved, dragged. Component MouseMotionEvent Key released, pressed, etc. Component KeyEvent User input through UI Components is processed via event-handling mechanism: Program waits for events to occur and then responds Firing an event when a source object generates an event Listener object that receives a notification of an event occurring. Event handler method that gets called in response to an event Listener Object must implement the appropriate Event handler method, specified by an in an appropriate listener interface (e.g. ActionListener, ItemListener, MouseEventListener, etc..) An event object contains whatever properties are pertinent to the event (the source component that fired the event, the time, etc ) You can identify the source object of the event using the getsource() instance method in the EventObject class Handling ActionEvents (generated by button-clicks, presses of Enter in TextArea, etc..) Register receiver (e.g. MathQuiz) as the listener object for the Button (or other source object). source.addactionlistener(receiver); The listener object (e.g.mathquiz ) must implement the ActionListener interface, i.e. provide definition of method public void actionperformed(actionevent e) Simple example: extending the SimpleFrame to react to ActionEvents - 4 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 5 of 12 /** * Simple Java program displaying a window.reacts to ActionEvents */ import java.awt.*; import javax.swing.*; public class SimpleFrame extends JFrame implements ActionListener { private JButton hi = new JButton("Hi"); private JButton exit = new JButton("Exit"); private JTextField tf = new JTextField(10); public SimpleFrame (){ // recall, the no arg constructor of superclas, // i.e. JFrame gets called here. this.setsize(450, 100); this.settitle("simple Action Listener"); this.setlocation(300, 300); this.setdefaultcloseoperation(exit_on_close); // tell it how to lay out components this.setlayout(new FlowLayout()); // add components this.add(new JLabel("Enter your name")); this.add(tf);this.add(hi); this.add(exit); // register this as a listener to action events // from the following components tf.addactionlistener(this); hi.addactionlistener(this); exit.addactionlistener(this); this.setvisible(true); /** Method required by the ActionListener interface * Is passed in an event as a parameter. * Performs an action based on the source of event. */ public void actionperformed(actionevent event) { if (event.getsource() == hi){ // hi button was pressed System.out.println("Hi, " + tf.gettext() + "!"); else if (event.getsource() == exit) { // exit button was pressed System.out.println("Bye, " + tf.gettext() + "!"); System.exit(0); else if (event.getsource() == tf) { // user pressed enter in the text field System.out.println("Nice to meet you, " + tf.gettext() + "!"); public static void main(string[] args) { // instantiate the class, will display a window new SimpleFrame(); - 5 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 6 of 12 Problem: create a simple graphical MathQuiz program that displays random problems, allows user to enter their answer, checks correctness. JRadioButton JLabel JButton JTextBox JTextArea /** MathQuizWindow.java The class implements a window with GUI components Shows how to add components to a frame. */ import java.awt.*; // helper classes like Color, LayoutManager, etc. import javax.swing.*; // library of components public class MathQuizWindow extends JFrame { // Define instance vars, simultaneously initializing them // by calling an appropriate constructor private JLabel label = new JLabel("Enter answer"); private JLabel lquestion = new JLabel(" a problem "); // to let user enter answer private JTextField tfanswer = new JTextField(15); cols //to show if correct or not, and correct answer if wrong private JTextArea answers = new JTextArea(2,20); //2 rows, 20 private JButton question = new JButton("Get question"); private JButton answer = new JButton("Submit"); private JButton exit = new JButton("Exit"); private JRadioButton add = new JRadioButton("Addition", true); private JRadioButton subtract = new JRadioButton("Subtraction", false); - 6 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 7 of 12 /** Constructor */ public MathQuizWindow (){ // recall: default superclass no-args // constructor is called here (i.e. JFrame ()) // creates a frame, initially invisible // set a few properties of the frame window this.setsize(250, 270); this.settitle("simple Math Quiz"); this.setdefaultcloseoperation(exit_on_close); //TO add the components to the container pane of the frame // 2. tell the frame how to arrange components: // using FlowLayout, componentes arranged around the center // by default this.setlayout(new FlowLayout()); // add radio buttons this.add(add); this.add(subtract); // Group radio buttons together in a group // to ensure *single* selection at any time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); // add other components this.add(question); this.add(lquestion); lquestion.setforeground(color.blue); this.add(label); this.add(tfanswer);this.add(answer); this.add(answers); this.add(exit); this.setvisible(true); public static void main(string[] args) { // Create an instance of the Math Quiz new MathQuizWindow (); Result: A frame that contains GUI components, but doesn t do anything in response - 7 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 8 of 12 If window is resized, components may be repositions relatively to each other because FlowLayout was used. To ensure relative positioning is the same use LayoutManager objects. Example: add functionality to the MathQuiz class on pages 4-5 to 1. Display a problem (see class Problem) in the TextField tfquestion when the Get Question button is pressed, according to the operation selected with the radio buttons. At the same time clear tfanswer and set cursor there. 2. Read contents of TextField tfanswer when the answer button is pressed, at the same time, display if answer was correct in the text area answers. /** Class Problem. Creates an arithmetical problem */ public class Problem { private int op1; private int op2; private char operator; // generate random operators public Problem(char operator){ this.op1 = 1+(int)(20 * Math.random()); //between 1 and 20 this.op2 = 1+(int)(20 * Math.random()); //between 1 and 20 this.operator = operator; // generate math problem public int getanswer(){ int answer; if (this.operator == '+') answer = op1 + op2; else if (this.operator == '-') answer = op1 - op2; else - 8 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 9 of 12 answer = op1 * op2; return answer; public String tostring(){ return op1 + " " + operator + " " + op2 + " =??"; public static void main (String [] args){ Problem p1 = new Problem('+'); System.out.println (p1); System.out.println (p1.getanswer()); Layout Managers Every container (JFrame, JPanel, JDialog) contains a LayoutManager object that determines relative positioning and size of components inside a container. Layout managers are assigned to a container using the setlayout(layoutmanager) method of a container. E.g. of LayoutManagers are FlowLayout, BorderLayout, GridLayout, GridBagLayout, and more classes. Useful tutoorilal on which to use and how: http://java.sun.com/docs/books/tutorial/uiswing/layout/using.html BorderLayout manager arranges components into five areas: East, South, West, North, and Center. Components are added to a BorderLayout by using the add method with an appropriate constraint add(component, constraint), where constraint is BorderLayout.EAST, BorderLayout.SOUTH, BorderLayout.WEST, BorderLayout.NORTH, or BorderLayout.CENTER. GridLayout manager arranges components in a grid (matrix) formation with the number of rows and columns defined by the constructor. Cosntructors: public GridLayout(int rows, int columns) - 9 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 10 of 12 Useful technique: Constructs a new GridLayout with the specified number of rows and columns. public GridLayout(int rows, int columns, int hgap, int vgap) Constructs a new GridLayout with the specified number of rows and columns, along with specified horizontal and vertical gaps between components. The components are placed in the grid from left to right starting with the first row, then the second, and so on. Can place components to panels (objects of type JPanel).You can also place panels in a panel. Then add those panels to the frame s (JFrame) content pane. Frame s contentpane Has BorderLayout questionpanel with 2 by 2 GridLayout answerpanel with FlowLayout, centered. - 10 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 11 of 12 /** The class implements a window with GUI components Shows how to add components in panels, using different layout managers. */ import java.awt.*; import javax.swing.*; // library of components public class MathQuizWindowWithPanels extends JFrame{ // Define instance vars, simultaneously initializing them private JLabel label = new JLabel("Enter answer"); private JLabel lquestion = new JLabel(" a problem "); // to let user enter answer private JTextField tfanswer = new JTextField(15); //to show if correct or not, and correct answer if wrong private JTextArea answers = new JTextArea (2, 20); private JButton question = new JButton("Get question"); private JButton answer = new JButton("Submit"); private JButton exit = new JButton("Exit"); private JRadioButton add = new JRadioButton("Addition", true); private JRadioButton subtract=new JRadioButton("Subtraction", false); /** Constructor */ public MathQuizWindowWithPanels (){ // recall: default superclass no-args // constructor is called here // creates a frame, initially invisible // set a few properties of the window this.setsize(350, 200); this.settitle("simple Math Quiz"); //TO add the components to the container pane of the frame // 1. get the content pane of the JFrame Container contentpane = this.getcontentpane(); // 2. tell the pane how to arrange components: //using BorderLayout with specified horiz. and vert.spacing contentpane.setlayout(new BorderLayout(5, 10)); JPanel questionpanel = createquestionpanel(); contentpane.add(questionpanel, BorderLayout.NORTH); JPanel answerpanel = createanswerpanel(); contentpane.add(answerpanel, BorderLayout.CENTER); contentpane.add(exit, BorderLayout.SOUTH); this.setvisible(true); - 11 -
Handout 12 CS603 Object-Oriented Programming Fall 15 Page 12 of 12 /** Creates a panel with question-related componenets */ private JPanel createquestionpanel(){ // create a panel JPanel qpanel = new JPanel(); // tell it to arrange components in 2 by 2 grid qpanel.setlayout(new GridLayout(2,2, 10, 10)); // add components to the panel in order left->right // top -> bottom // add radio buttons qpanel.add(add); qpanel.add(subtract); qpanel.add(question); lquestion.setforeground(color.blue); qpanel.add(lquestion); // Group radio buttons together in a group // to ensure *single* selection at any time: ButtonGroup operations = new ButtonGroup(); operations.add(add); operations.add(subtract); return qpanel; /** Creates a panel with answer-related componenets */ private JPanel createanswerpanel(){ // create a panel JPanel apanel = new JPanel(); apanel.setlayout(new FlowLayout()); apanel.add(label); apanel.add(tfanswer); apanel.add(answer); apanel.add (answers); return apanel; public static void main(string[] args) { // Create an instance of the Math Quiz new MathQuizWindowWithPanels (); - 12 -