Download presentation
Presentation is loading. Please wait.
Published bySamuel Bishop Modified over 8 years ago
1
GUI 1: JFC and Swing Basics OOP tirgul No. 4 2009
2
Swing Packages javax.accessibilityjavax.swing.plafjavax.swing.text javax.swingjavax.swing.plaf.basicjavax.swing.text.html javax.swing.borderjavax.swing.plaf.metaljavax.swing.text.html.parser javax.swing.colorchooserjavax.swing.plaf.multijavax.swing.text.rtf javax.swing.eventjavax.swing.plaf.synthjavax.swing.tree javax.swing.filechooserjavax.swing.tablejavax.swing.undo
3
Hello Swing import javax.swing.*; public class HelloWorldSwing { public static void main(String[] args) { //Create and set up the window JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Add the ubiquitous "Hello World" label JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); //Resize window to fit preferred size and subcomponents layouts frame.pack(); //Display the window frame.setVisible(true); }
4
Swing components Windows Panels Individual components Except top-level containers, all Swing components whose names begin with "J" descend from the JComponent class that extends the java.awt. Container class, which itself extends java.awt.Component.
5
Swing containment hierarchy Composite design pattern A containment hierarchy is a tree of components that has a top-level container as its root. Swing provides three generally useful top-level container classes: JFrame, JDialog & JApplet. To appear onscreen, every GUI component must be part of a containment hierarchy. Each GUI component can be contained only once. Each top-level container has a content pane that contains (directly or indirectly) the visible components in that top-level container's GUI.
6
Anatomy of an Application GUI JPanel JButton JFrame JLabel Appearance Internal structure JFrame JPanel JButtonJLabel containers components
7
Example 2: HelloWorldSwing2 public static void main(String[] args) { JFrame.setDefaultLookAndFeelDecorated(true); JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel panel = new JPanel(); JButton button = new JButton("click me!"); JButton button = new JButton("click me!"); panel.add(button); panel.add(button); panel.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 20)); panel.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 20)); frame.add(panel); frame.pack(); frame.setVisible(true); }
8
Creating a GUI Component Create it Jbutton b = new JButton(“press me”); Configure it b.setText(“press me too”); Add it panel.add(b); Listen to it/bind it to other components … JButton
9
Java Beans JavaBeans enable developers to create components - self-contained, reusable software units that can be visually assembled into composite components Properties are the appearance and behavior characteristics of a bean that can be changed at design time. Builder tools introspect on a bean to discover its properties and expose those properties for manipulation by a process known as introspection Beans support introspection by adhering to naming conventions – specific rules for naming bean features Beans use events to communicate with other beans. A bean that is to receive events (a listener bean) registers with the bean that fires the event (a source bean).
10
Java Bean example public class MyBean { /** Creates a new instance of MyBean */ public MyBean() { } /** Holds value of property title. */ private String title; /** Getter for property title. * @return Value of property title. */ public String getTitle() { return this.title; } /** Setter for property title. * @param title New value of property title. */ public void setTitle(String title) { this.title = title; } } extends javax.swing.JComponent { protected void paintComponent(java.awt.Graphics g) { … } }
11
Swing controls JButton JCheckBox JComboBoxJList JRadioButton JSlider JSpinner JTextField JPasswordField JTextArea JTree JTable JLabel JProgressBar JSeparator JToolTip
12
Swing containers JPanel JScrollPane JSplitPane JTabbedPane JToolBar JInternalPane JLayeredlPane
13
JMenu Menu bar can be added to a top-level container, it is positioned outside the content pane.
14
Layout Managers Left to right, Top to bottom c n s ew FlowLayoutGridLayout BorderLayout none, programmer sets x,y,w,h null One at a time CardLayout GridBagLayout JButton
15
Layout Combinations NORTH JPanel : BorderLayoutSOUTHNORTH SOUTH JFrame JPanel: FlowLayout JButton JTextArea
16
Layout Combinations Panel panel1 = new JPanel(new FlowLayout()); panel1.add(new JButton("JButton")); JPanel panel2 = new JPanel(new BorderLayout()); panel2.add(panel1,BorderLayout.NORTH); panel2.add(new TextArea(5,15),BorderLayout.SOUTH); frame.add(panel2);
17
Events and Listeners The Hollywood principle: “Don’t call us, we’ll call you” Observer design pattern – – Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. – The key objects in this pattern are subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in state.
18
Adding an Action Listener import java.awt.event.*; … JButton button = new JButton("click me!"); button.addActionListener(new ButtonActionListener()); … class ButtonActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.out.println("command: " + e.getActionCommand()); } Adding a listener to the button : Defining the listener : command: click me! public interface ActionListener { void actionPerformed(ActionEvent e); }
19
More complex scenario Any number of event listener objects can listen for all kinds of events from any number of event source objects. Multiple listeners can register to be notified of events of a particular type from a particular source. Also, the same listener can listen to notifications from different objects. Each event is represented by an object that gives information about the event and identifies the event source.
20
MouseListener Inteface class MouseListener1 implements MouseListener{ public void mouseClicked(MouseEvent e) { System.out.println(e.getX()+","+e.getY()); } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} } But we only wanted mouseClicked() …
21
Mouse Adapter class MouseAdapter1 extends MouseAdapter { public void mouseClicked(MouseEvent e) { System.out.println(e.getX()+","+e.getY()); } An empty implementation of MouseListener
22
Some common listeners component listener listens for changes in the component's size, position, or visibility. focus listener listens for whether the component gained or lost the keyboard focus. key listener listens for key presses; key events are fired only by the component that has the current keyboard focus. mouse listener listens for mouse clicks, mouse presses, mouse releases and mouse movement into or out of the component's drawing area. mouse-motion listener listens for changes in the mouse cursor's position over the component. hierarchy listener Listens for changes to a component's containment hierarchy of changed events. property change listeners listen for changes to bound properties and are used by several Swing components vetoable change listeners are used by builder tools to listen for changes on constrained properties
23
Concurrency Careful use of concurrency is particularly important to the Swing programmer. A well-written Swing program creates a user interface that never "freezes" — the program is always responsive to user interaction, no matter what it's doing. A Swing programmer deals with the following kinds of code executions: ◦ initial application code; ◦ event-handling, most code that interacts with the Swing framework must execute there; ◦ time-consuming background tasks.
24
Event Dispatcher Thread (EDT) It is a background processing mechanism to process events from graphical user interface event queue. These events are primarily update events that cause user interface components to redraw themselves, or input events from input devices such as the mouse or keyboard. Swing uses a painting model in which all screen updates must be performed sequentially. The event dispatching thread is the only valid way to update the state of visible user interface components.
25
SwingUtilities Command design pattern invokeLater and invokeAndWait ◦ take a single argument: the Runnable that defines the new task. ◦ invokeLater schedules the task and returns ◦ invokeAndWait waits for the task to finish before returning SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });
26
Hello Swing revisited public class HelloWorldSwing { public static void main(String[] args) { SwingUtilities.invokeLater( new Runnable() { public void run() { } ); } JFrame frame = new JFrame("HelloWorldSwing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JLabel label = new JLabel("Hello World"); frame.getContentPane().add(label); frame.pack(); frame.setVisible(true);
27
Summary Swing JavaBeans Components Containers Layouts Events Concurrency Find out more: http://java.sun.com/docs/books/tutorial/uiswing/index.html http://java.sun.com/docs/books/tutorial/uiswing/index.html
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.