Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS3340: Swing and Event handling L. Grewe. Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel,

Similar presentations


Presentation on theme: "CS3340: Swing and Event handling L. Grewe. Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel,"— Presentation transcript:

1 CS3340: Swing and Event handling L. Grewe

2 Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel, JButton, JScrollBar, JApplet, etc.. Most Swing Components are “Lightweight” Use Java code rather than native code to draw in the underlying window. The Exceptions are JFrame, JApplet, JWindow, and JDialog Use Content Pane for adding Components to “Heavyweight” Containers To add Components to a JApplet (in method init( )) use Container cp = new getContentPane( ); cp.add(new JButton(“Start”);

3 Swing Differences between Swing and AWT Components Use of paintComponent for Drawing public void paintComponent(Graphics g) { super.paintComponent(g); //always call super.paintComponent( ) before performing custom drawing // draw Shape on the Swing Component } Double Buffering In Swing a JPanel is used instead of a Canvas to be the target for drawing graphics objects. When drawing to a JPanel using paintComponent double buffering is automatically employed. There is an option to perform drawing directly to the screen using the paint method by using panel.getGraphics( );

4 Anatomy of a Java Swing GUI JFrame JFrame JPanel JPanel Layout Manager Layout Manager JComponents JComponents JPanel JButton JFrame Layout Manager

5 Build from bottom up Create: Create: Frame Frame Panel Panel Layout manager Layout manager Components Components Listeners Listeners Add: (bottom up) Add: (bottom up) layout manager to panel layout manager to panel listeners to components listeners to components components to panel components to panel panel to frame panel to frame JPanel JButton Layout Listener JFrame

6 Code JFrame f = new JFrame(“title”) JPanel p = new JPanel( ); JButton b = new JButton(“press me”); p.add(b); // add button to panel f.setContentPane(p); // add panel to frame f.setVisible(true);

7 General-Purpose Containers Intermediate containers which can be used under many different circumstances: Intermediate containers which can be used under many different circumstances: Panel (JPanel)Panel (JPanel) Scroll pane (JScrollPane)Scroll pane (JScrollPane) Split paneSplit pane Tabbed paneTabbed pane Tool barTool bar

8 General Purpose Containers Panel—most flexible and frequently used. Add almost no functionality beyond what all objects have. Often used to group components. Panel—most flexible and frequently used. Add almost no functionality beyond what all objects have. Often used to group components. Scroll pane—provides scroll bars around a large or growable component. Scroll pane—provides scroll bars around a large or growable component. Split pane—displays two components in a fixed amount of space, letting the user adjust the amount of space devoted to each component. Split pane—displays two components in a fixed amount of space, letting the user adjust the amount of space devoted to each component.

9 General Purpose Containers Tabbed pane—contains multiple components but show only one at a time. The user can easily switch between components. Tabbed pane—contains multiple components but show only one at a time. The user can easily switch between components. Tool bar—holds a group of components (usually buttons) in a row or column, optionally allowing the user to drag the tool bar into different locations. Tool bar—holds a group of components (usually buttons) in a row or column, optionally allowing the user to drag the tool bar into different locations.

10 General-Purpose Containers Panel Scroll Pane Tool bar Split pane Tabbed pane

11 Special-Purpose Containers Intermediate containers that play specific roles in the use interface. Intermediate containers that play specific roles in the use interface. Internal frame— Able to display display a Frame-like window within another window. Usually, you add internal frames to a desktop pane.Internal frame— Able to display display a Frame-like window within another window. Usually, you add internal frames to a desktop pane. Layered frame—Provides a third dimension for positioning components: depth, also known as Z order.Layered frame—Provides a third dimension for positioning components: depth, also known as Z order. Root pane—Has 4 parts: glass pane, layered pane, content pane, and the (optional) menu bar.Root pane—Has 4 parts: glass pane, layered pane, content pane, and the (optional) menu bar.

12 Special-Purpose Containers Internal Frame Layered Pane Root Pane

13 Layout Managers Review -layout managers: Review -layout managers: null (no manager, programmer sets x,y,w,h) null (no manager, programmer sets x,y,w,h) Flowlayout Flowlayout GridLayout GridLayout BorderLayout BorderLayout c n s ew

14 Code JFrame f = new JFrame(“title”) JPanel p = new JPanel( ); JButton b = new JButton(“press me”); b.setBounds(new Rectangle(10,10, 100,50)); p.setLayout(null);// x,y layout p.add(b);f.setContentPane(p);

15 15 An example nested layout Container container = new JFrame() or JApplet() ; JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, E JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); // also add buttons G, H, I, J, K JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); // also add buttons M, N, O, P container.setLayout(new BorderLayout()); container.add(p1, BorderLayout.CENTER); container.add(p2, BorderLayout.SOUTH); container.add(p3, BorderLayout.EAST); Container container = new JFrame() or JApplet() ; JPanel p1 = new JPanel(); p1.setLayout(new BorderLayout()); p1.add(new JButton("A"), BorderLayout.NORTH); // also add buttons B, C, D, E JPanel p2 = new JPanel(); p2.setLayout(new GridLayout(3, 2)); p2.add(new JButton("F")); // also add buttons G, H, I, J, K JPanel p3 = new JPanel(); p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS)); p3.add(new JButton("L")); // also add buttons M, N, O, P container.setLayout(new BorderLayout()); container.add(p1, BorderLayout.CENTER); container.add(p2, BorderLayout.SOUTH); container.add(p3, BorderLayout.EAST);

16 Components Buttons—can be square or roundButtons—can be square or round Combo Box—can be uneditable and editable.Combo Box—can be uneditable and editable. List—Presents the user with a group of items, displayed in a column, to choose from.List—Presents the user with a group of items, displayed in a column, to choose from. Menu—provides a space-saving way to let the user choose one of several options.Menu—provides a space-saving way to let the user choose one of several options. Slider—lets user enter a numeric value bounded by a minimum and maximum value.Slider—lets user enter a numeric value bounded by a minimum and maximum value. Text Fields—basic text control that lets the user enter a small amount of text.Text Fields—basic text control that lets the user enter a small amount of text.

17 Basic Components Buttons Combo Box List Menu SliderText Fields

18 More Components – not selectable Atomic components that exist solely to give the user information. Atomic components that exist solely to give the user information. Label—able to display unselectable text and images.Label—able to display unselectable text and images. Progress Bar—displays the progress of a long-running task (also, ProgressMonitor and ProgressMonitorInputStream)Progress Bar—displays the progress of a long-running task (also, ProgressMonitor and ProgressMonitorInputStream) Tool tip—comes up when the user of the program pauses with the cursor over any of the program's buttonsTool tip—comes up when the user of the program pauses with the cursor over any of the program's buttons

19 Uneditable Information Displays Tool Tips Progress Bar Label

20 Editable Displays of Formatted Information Atomic components that display highly formatted information that can be edited by the user. Atomic components that display highly formatted information that can be edited by the user. Color chooser—provide users with a palette of colors to choose from.Color chooser—provide users with a palette of colors to choose from. File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name.File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name. Table—displays tables of data, optionally allowing the user to edit the data.Table—displays tables of data, optionally allowing the user to edit the data. Text—displays text and allows user to edit itText—displays text and allows user to edit it Tree—displays data in hierarchical wayTree—displays data in hierarchical way

21 Editable Displays of Formatted Information File Chooser Color Chooser Table Text Tree

22 Editable Displays of Formatted Information Atomic components that display highly formatted information that can be edited by the user. Atomic components that display highly formatted information that can be edited by the user. Color chooser—provide users with a palette of colors to choose from.Color chooser—provide users with a palette of colors to choose from. File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name.File chooser—provide a GUI for navigating the file system, and then either choosing a file or directory from a list or entering a file name or directory name. Table—displays tables of data, optionally allowing the user to edit the data.Table—displays tables of data, optionally allowing the user to edit the data. Text—displays text and allows user to edit itText—displays text and allows user to edit it Tree—displays data in hierarchical wayTree—displays data in hierarchical way

23 Editable Displays of Formatted Information File Chooser Color Chooser Table Text Tree

24 Events How to handle user events related to GUI components How to handle user events related to GUI components

25 Events Register with a component to receive events Register with a component to receive events Give component a ref to a Listener object Give component a ref to a Listener object ActionListener ActionListener KeyListener KeyListener MouseListener MouseListener WindowListener WindowListener … JButton Listener click ActionEvent register

26 Code myListener = new myListenClass; btn.addActionListener(myListener); Class myListenClass implements ActionListener { public void actionPerformed(ActionEvent e){ // button pressed, do stuff here }}

27 Simplifying: Inheritance Class myframe extends JFrame{ public myframe(){ // create panel, buttons, … setContentPane(p);// I am a jframe } public static void main(){ JFrame f = new myframe(); }} Myframe creates JFrame via inheritance Myframe creates JFrame via inheritance

28 Simplifying: Inheritance Class myframe extends JFrame{ public myframe(){ // create panel, buttons, … } public static void main(){ JFrame f = new myframe(); } public void paint(Graphics g){ super.paint(g); //call overriden method // paint stuff here }} Override JFrame methods to add functionality Override JFrame methods to add functionality

29 Simplifying: Implements Class myframe extends JFrame implements ActionListener { public myframe(){ // create panel, buttons, … btn.addActionListener(this); } public void actionPerformed(ActionEvent e){ // button pressed, do stuff here }}

30 Simplifying: Anonymous classes Class myframe extends JFrame { public myframe(){ // create panel, buttons, … btn.addActionListener( new ActionListener() { new ActionListener() { public void actionPerformed(ActionEvent e){ public void actionPerformed(ActionEvent e){ // button pressed, do stuff here // button pressed, do stuff here } });}} Defining and instantiating a class on the fly

31 31 Components use various listeners JButton, JMenuItem, JComboBox, JTextField: JButton, JMenuItem, JComboBox, JTextField: addActionListener(ActionListener)addActionListener(ActionListener) public void actionPerformed(ActionEvent event) public void actionPerformed(ActionEvent event) JCheckBox, JRadioButton: JCheckBox, JRadioButton: addItemListener(ItemListener)addItemListener(ItemListener) public void itemStateChanged(ItemEvent event) public void itemStateChanged(ItemEvent event) JSlider JSlider addChangeListener(ChangeListener)addChangeListener(ChangeListener) public void stateChanged(ChangeEvent event) public void stateChanged(ChangeEvent event) JTextArea JTextArea getDocument().addDocumentListener(DocumentListener)getDocument().addDocumentListener(DocumentListener) public void insertUpdate(DocumentEvent event) public void insertUpdate(DocumentEvent event) public void removeUpdate(DocumentEvent event) public void removeUpdate(DocumentEvent event) public void changedUpdate(DocumentEvent event) public void changedUpdate(DocumentEvent event)

32 32 Components- Getting values Some user actions normally cause the program to do something: clicking a button, or selecting from a menu Some user actions normally cause the program to do something: clicking a button, or selecting from a menu Some user actions set values to be used later: entering text, setting a checkbox or a radio button Some user actions set values to be used later: entering text, setting a checkbox or a radio button You can listen for events from these, but it’s not usually a good ideaYou can listen for events from these, but it’s not usually a good idea Instead, read their values when you need themInstead, read their values when you need them String myText = myJTextField.getText(); String myText = myJTextField.getText(); String myText = myJTextArea.getText(); String myText = myJTextArea.getText(); boolean checked = myJCheckBox.isSelected(); boolean checked = myJCheckBox.isSelected(); boolean selected1 = myJRadioButton1.isSelected(); boolean selected1 = myJRadioButton1.isSelected();

33 33 Components - Enabling and disabling It is poor style to remove components you don’t want the user to be able to use It is poor style to remove components you don’t want the user to be able to use “Where did it go? It was here a minute ago!”“Where did it go? It was here a minute ago!” Exception – changing to new interfaceException – changing to new interface It’s better to enable and disable controls It’s better to enable and disable controls Disabled controls appear “grayed out”Disabled controls appear “grayed out” The user may still wonder why?, but that’s still less confusingThe user may still wonder why?, but that’s still less confusing anyComponent.setEnabled( enabled ); anyComponent.setEnabled( enabled ); Parameter should be true to enable, false to disableParameter should be true to enable, false to disable

34 An example

35 Example 1 – an applet with 3 buttons and 2 text fields Step1 – Design the interface Read Write Clear Enter text Correct Entry? Applet The JApplet will consist of 2 JPanels – The top one containing labels and text fields The bottom one containing three JButtons The browser will add a title bar when the applet is running

36 Swing ReadWriteClear Enter text Correct Entry? Applet The top Panel will use a GridLayout with 2 rows and 2 columns (with a separation of 10 pixels)

37 Swing Example 1 //(global) attributes of the class private MyJTextField source = new MyJTextField(25); private MyJTextField target = new MyJTextField(25); private JLabel edit = new JLabel("Enter text"); private JLabel verify = new JLabel("Correct Entry?"); private String inStr = new String(""); //method to construct the top panel private JPanel makeJTextPanel( ) { JPanel theText = new JPanel( ); theText.setLayout(new GridLayout(2,2, 10, 10)); theText.add(edit); theText.add(source); theText.add(verify); theText.add(target); return theText; } Construct the top panel – write a method makeJTextPanel( ) Add components to the grid – left to right, top to bottom

38 Swing Example 1 ReadWriteClear Enter text Correct Entry? Applet Construct the bottom Panel – Use FlowLayout (center adjusted) Top JPanel Bottom JPanel

39 Swing Example 1 Construct the bottom panel – with a method private MyJButton read; private MyJButton write; private MyJButton clear; //build the bottom panel with method makeJButtonPanel( ) private JPanel makeJButtonPanel() { read = new MyJButton ("Read", source); write = new MyJButton("Write", target); clear = new MyJButton("Clear", target); JPanel theButtons = new JPanel( ); theButtons.setLayout(new FlowLayout(FlowLayout.CENTER)); theButtons.add(read); theButtons.add(write); theButtons.add(clear); theButtons.setBackground(Color.blue); return theButtons; } Create the bottom panel Set its layout and color, and add the buttons to it (left to right)

40 Swing Example 1 Place the panels into the applet in method init( ) public void init( ) { Container cp = getContentPane( ); theButtons = makeJButtonPanel( ); cp.add(BorderLayout.SOUTH, theButtons); theText = makeJTextPanel( ); cp.add(BorderLayout.CENTER, theText); } For heavyweight component like JApplet components must be added to a ContentPane //add theButtons (a JPanel) to the ContentPane //the default LayoutManager of a JApplet is BorderLayout

41 MyJButton objects interact with MyJTextField objects Swing Example 1 Design of the System A button event will cause a read, write, or clear of a text field. JPanelJApplet MyJTextField MyJTextField(int size) doButtonAct(MyJButto n) String response MyJButton JLabel MyJButton(String, MyJTextField) actionPerformed(ActionEvent) MyJTextField target ActionListener activates The applet is an aggregate of 2 JPanels 2 32 describes JPanels contain JLabels and MyJTextField objects OR MyJButtons

42 Swing Example 1 class MyJButton extends JButton implements ActionListener { private MyJTextField target; public MyJButton(String name, MyJTextField targ) { Font buttonFont = new Font ("Times Roman", Font.BOLD, 12); setFont(buttonFont); setText(name); setBackground(Color.cyan); target = targ; addActionListener(this); } public void actionPerformed(ActionEvent e) { target.doButtonAct(this); } class MyJButton Constructor receives handle to text field Hold handle to target text field Event causes message to be sent to the target to perform a read or write

43 Swing Example 1 class MyJTextField extends JTextField { private String response = new String( ); public MyJTextField(int size) { super(size); } public void doButtonAct(MyJButton source) { response = source.getText( ); if (response.equals("Read") ) inStr = super.getText( ); else if (response.equals("Write") ) setText(inStr); else if (response.equals("Clear") ) setText(""); } A MyJButton object notifies a MyJTextField of a button event and elicits an action

44 Now some more Classes Lets examine a few classes in more details Lets examine a few classes in more details

45 Swing And JScrollPane Adding scroll bars to a component such as a JTextArea Just wrap a JTextArea object inside a JScrollPane. JTextArea ta = new JTextArea(10, 25); JScrollPane sp = new JScrollPane(ta); The programmer can control which scrollbars are allowed – vertical, horizontal, both, or neither JScrollPane sp = new JScrollPane(ta, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

46 46Dialogs A dialog (small accessory window) can be modal or nonmodal A dialog (small accessory window) can be modal or nonmodal When your code opens a modal dialog, it waits for a result from the dialog before continuingWhen your code opens a modal dialog, it waits for a result from the dialog before continuing When your code opens a nonmodal dialog, it does so in a separate thread, and your code just keeps goingWhen your code opens a nonmodal dialog, it does so in a separate thread, and your code just keeps going Sun supplies a few simple (but useful) modal dialogs for your use Sun supplies a few simple (but useful) modal dialogs for your use You can create your own dialogs (with JDialog ), but they are nonmodal by default You can create your own dialogs (with JDialog ), but they are nonmodal by default

47 47 Message dialogs JOptionPane.showMessageDialog(parentJFrame, "This is a JOptionPane \"message\" dialog."); JOptionPane.showMessageDialog(parentJFrame, "This is a JOptionPane \"message\" dialog."); Notice that showMessageDialog is a static method of JOptionPane Notice that showMessageDialog is a static method of JOptionPane The “ parentJFrame ” is typically your main GUI window (but it’s OK to use null if you don’t have a main GUI window) The “ parentJFrame ” is typically your main GUI window (but it’s OK to use null if you don’t have a main GUI window)

48 48 Confirm dialogs int yesNo = JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to see?"); int yesNo = JOptionPane.showConfirmDialog(parentJFrame, "Is this what you wanted to see?"); if (yesNo == JOptionPane.YES_OPTION) {... } if (yesNo == JOptionPane.YES_OPTION) {... }

49 49 Input dialogs String userName = JOptionPane.showInputDialog(parentJFrame, "What is your name?") String userName = JOptionPane.showInputDialog(parentJFrame, "What is your name?")

50 50 Option dialogs Object[] options = new String[] {"English", "Chinese", "French", "German" }; int option = JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default Object[] options = new String[] {"English", "Chinese", "French", "German" }; int option = JOptionPane.showOptionDialog(parentJFrame, "Choose an option:", "Option Dialog", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); // use as default Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION Fourth argument could be JOptionPane.YES_NO_CANCEL_OPTION Fifth argument specifies which icon to use in the dialog; it could be one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or PLAIN_MESSAGE Fifth argument specifies which icon to use in the dialog; it could be one of ERROR_MESSAGE, INFORMATION_MESSAGE, WARNING_MESSAGE, or PLAIN_MESSAGE Sixth argument ( null above) can specify a custom icon Sixth argument ( null above) can specify a custom icon

51 51 Load file dialogs JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Load which file?"); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle("Load which file?"); int result = chooser.showOpenDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } int result = chooser.showOpenDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } You could also test for CANCEL_OPTION or ERROR_OPTION You could also test for CANCEL_OPTION or ERROR_OPTION You will get back a File object; to use it, you must know how to do file I/O You will get back a File object; to use it, you must know how to do file I/O

52 52 Save file dialogs JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(“Save file as?"); JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(“Save file as?"); int result = chooser.showSaveDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } int result = chooser.showSaveDialog(enclosingJFrame); if (result == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); // use file } You could also test for CANCEL_OPTION or ERROR_OPTION You could also test for CANCEL_OPTION or ERROR_OPTION You will get back a File object; to use it, you must know how to do file I/O You will get back a File object; to use it, you must know how to do file I/O


Download ppt "CS3340: Swing and Event handling L. Grewe. Swing Differences between Swing and AWT Naming Conventions All Swing components begin with a capital J -- JPanel,"

Similar presentations


Ads by Google