עקרונות תכנות מונחה עצמים תרגול 4 - GUI
Outline Introduction to GUI Swing Basic components Event handling
CLI VS GUI
GUI applicationsCLI applications Reactive, interactiveTransactionalProgram Flow AsynchronousTextualInput GraphicalTextualOutput YesNoMultiTasking Remains activeExitAfter Execution
GUI programming challenges Usability Attractiveness Multithreading Incremental execution Testing And The algorithm
Elements of GUI programming Visualization of data: Model Widgets Visualization of commands: Buttons, pop-ups Responding of commands: Event handling Graphical layout: Containers, panels, layout managers Reactiveness: Using threads safely Separation of concerns: OOP, good design, MVC
SWING Java’s GUI framework (Java Foundation Classes) Extension of an older framework – AWT Provides: Frames, dialogs, panels, toolbars.. Graphical control widgets, from buttons to tree controls Thread-safe events dispatching Rich-text editing Pluggable Look-n’-feel(PLAF) Other goodies (accessibility, text parsing..) Official Swing Tutorial
Swing Elements Components - Graphical widgets Containers -Components that contain sub-components Layout - Arrangement of components inside containers Events - Interaction with the user Event listeners – Objects that responds to events asynchronously Event dispatcher – A special thread that dispatches events and re-paints the GUI Models - Objects that hold the data and handle events for components
Swing components - hierarchy Each component is a Java class with a fairly extensive inheritency hierarchy: Object Component Container JComponent JPanel Window Frame JFrame javax.swing java.awt java.lang
Using Swing Components Very simple, just create object from appropriate class – examples: JButton but = new JButton(); JTextField text = new JTextField(); JTextArea text = new JTextArea(); JLabel lab = new JLabel(); Many more classes. Don’t need to know every one to get started.
Adding components Once a component is created, it can be added to a container by calling the container’s add method: Container cp = getContentPane(); cp.add(new JButton(“cancel”)); cp.add(new JButton(“go”)); How these are laid out is determined by the layout manager (next lesson).
JFrame A frame contains: Title bar Menu bar Content pane The content pane is a container that represent the main area of the frame.
Example 1 Hello.jar
Jhello World! public class Hello extends JFrame { public Hello(){ super("Title Bar"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton click = new JButton("This is a button"); Container cp = getContentPane(); cp.add(click); pack(); setVisible(true); } public static void main(String args[]){ Hello frame = new Hello(); }
Event handling
Events and Listeners in Swing Input from the user in Swing is represented by Events Events come from a Source: a component or a model Related kinds of inputs are grouped into Listener interfaces A listener interface contains several messages that passes events to the receiver Each message represent a different scenario of receiving this input from the user An Event Listener is an object whose class implements a listener interface, so it can receive events Attaching a listener of type X to a source is done by the call : source.addXListener(listener)
Example 2 Jumper.jar
Add Action Listener public class Jumper extends JFrame implements ActionListener{ public Jumper(){ super(“Jumper"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton btn = new JButton(“Catch me!"); btn.addActionListener(this); // source.addXListener(listener) Container cp = getContentPane(); cp.add(btn); pack(); setVisible(true); public void actionPerformed(ActionEvent e) { Random rand = new Random(); int x = rand.nextInt(300); int y = rand.nextInt(300); setLocation(x, y); }
The Event object All event classes in Swing extends the EventObject class. This class contains the method getSource( ) that returns the object which was the source of the event Events sub-classes usually also contain data related to specific event.
Event Listener Example: Action Listener
Event Listener Example: Mouse Listener
Listening to an event
Example 3 Convertor.jar
public class Convertor extends JFrame implements ActionListener { private static double DOLLAR_RATE = 3.943; private JButton convertButton; private JButton resetButton; private JLabel resultLabel; private JTextField valueInput; private double value; public Convertor(){ super("Convertor"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); value = 0; // Initiate label and text field. valueInput = new JTextField(); valueInput.setColumns(10); valueInput.setText( value + ""); resultLabel = new JLabel(value + " $ is "+ convert() + " Shekel"); // Create buttons convertButton = new JButton("Convert"); resetButton = new JButton("Reset");
// Add action listeners convertButton.addActionListener(this); resetButton.addActionListener(this); // Add all objects to Content Pane getContentPane().setLayout(new FlowLayout()); getContentPane().add(resetButton); getContentPane().add(valueInput); getContentPane().add(convertButton); getContentPane().add(resultLabel); pack(); setVisible(true); {
public void actionPerformed(ActionEvent e) { if (e.getSource().equals(convertButton)){ updateValue(); } if (e.getSource().equals(resetButton)){ setValue(0); } updateView(); { private void setValue(double v) { this.value = v; } private double convert() { return value*DOLLAR_RATE; { private void updateValue(){ this.value = Double.parseDouble(valueInput.getText()); } private void updateView(){ resultLabel.setText(value +" $ is " + convert() + " Shekel " ); valueInput.setText(value +""); pack(); {