Your SlideShare is downloading. ×
Swing
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Saving this for later?

Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime - even offline.

Text the download link to your phone

Standard text messaging rates apply

Swing

1,422
views

Published on


0 Comments
4 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,422
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
0
Comments
0
Likes
4
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Swing
  • 2. Using Swing Components
  • 3. JFrame & JLabel Hierarchy javax.swing.JFrame java.awt.Frame java.awt.Window java.awt.Container java.awt.Component java.awt.Object javax.swing.JLabel JComponent
  • 4. JTextField & JButton Hierarchy javax.swing.JButton javax.swing.AbstractButton javax.swing.JComponent JTextField javax.swing.text.JTextComponent javax.swing.JToggleButton JCheckBox JRadioButton JTextArea JEditorPane JTextPane
  • 5. Creating a Window
  • 6. Creating a Window contd.
    • import javax.swing.*;
    • public class SwingTest extends JFrame
    • {
    • public SwingTest( String title )
    • {
    • super(title);
    • setSize(500,350);
    • setVisible(true);
    • }
    • public static void main(String[] args)
    • {
    • SwingTest window = new SwingTest("Swing Demo");
    • }
    • }
  • 7. Adding Components to a Window
    • public SwingTest( String title )
    • {
    • super(title);
    • setSize(500,350);
    • setVisible(true);
    • firstName = new JTextField(20);
    • lastName = new JTextField(20);
    • fullName = new JButton("Full Name");
    • first = new JLabel("First Name");
    • last = new JLabel("Last Name");
    • setLayout(new FlowLayout());
    • add(first); add(firstName);
    • add(last); add(lastName);
    • add(fullName);
    • }
  • 8. Adding Components to a Window
  • 9. Events java.awt.event.FocusEvent java.awt.event.MouseEvent java.awt.event.WindowEvent java.awt.event.ActionEvent java.awt.event.ComponentEvent java.awt.AWTEvent java.util.EventObject java.lang.Object
  • 10. Event Listeners java.awt.event.MouseListener java.util.EventListener java.util.EventListener java.awt.event.ActionListener java.awt.event.FocusListener java.awt.event.WindowListener
  • 11. Registering a Component with a Listener
    • import java.awt.event.*;
    • public class SwingTest extends JFrame implements ActionListener
    • {
    • public SwingTest( String title )
    • {
    • fullName.addActionListener(this);
    • }
    • public void actionPerformed(ActionEvent ae)
    • {
    • String fullName = firstName.getText()+" "+lastName.getText();
    • JOptionPane.showMessageDialog(null,fullName);
    • }
    • }
    Registering the button with ActionListener to handle ActionEvent
  • 12. Registering a Component with a Listener
    • public class SwingTest extends JFrame implements ActionListener,MouseListener
    • {
    • public SwingTest( String title )
    • {
    • fullName.addActionListener(this);
    • fullName.addMouseListener(this);
    • }
    • public void actionPerformed(ActionEvent ae)
    • {
    • String fullName = firstName.getText()+" "+lastName.getText();
    • JOptionPane.showMessageDialog(null,fullName);
    • }
    • public void mouseEntered(MouseEvent me)
    • {
    • System.out.println("mouse enter event");
    • }
    Registering the button with MouseListener to handle MouseEvent
  • 13. Registering a Component with a Listener
    • public void mouseExited(MouseEvent me)
    • {
    • System.out.println("mouse exit event");
    • }
    • public void mousePressed(MouseEvent me)
    • {
    • System.out.println("mouse press event");
    • }
    • public void mouseReleased(MouseEvent me)
    • {
    • System.out.println("mouse release event");
    • }
    • public void mouseClicked(MouseEvent me)
    • {
    • System.out.println("mouse click event");
    • }
    • }
    Registering the button with MouseListener to handle MouseEvent contd. Which is preferrable? MouseListener or ActionListener
  • 14. Registering a Component with a Listener Registering TextFields with FocusListener to handle FocusEvent
  • 15. Registering a Component with a Listener
    • public class SwingTest extends JFrame implements ActionListener,FocusListener
    • {
    • Color backGround;
    • public SwingTest( String title )
    • {
    • fullName.addActionListener(this);
    • firstName.addFocusListener(this);
    • lastName.addFocusListener(this);
    • backGround = firstName.getBackground();
    • }
    • public void focusGained(FocusEvent fe)
    • {
    • ((JComponent)fe.getSource()).setBackground(new Color(255,255,193));
    • }
    • public void focusLost(FocusEvent fe)
    • {
    • ((JComponent)fe.getSource()).setBackground(backGround);
    • }
    • }
  • 16. Using Mnemonic to transfer focus
  • 17. Using Mnemonic to transfer focus
    • n = new JLabel("Name");
    • r = new JLabel("Roll");
    • b = new JLabel("Batch");
    • s = new JLabel("Session");
    • n.setDisplayedMnemonic('N');
    • r.setDisplayedMnemonic('R');
    • b.setDisplayedMnemonic('B');
    • s.setDisplayedMnemonic('S');
    • n.setLabelFor(name);
    • r.setLabelFor(roll);
    • b.setLabelFor(batch);
    • s.setLabelFor(session);
  • 18. Adding ToolTips
    • b1 = new JButton();
    • b2 = new JButton();
    • b3 = new JButton();
    • b1.setToolTipText("Hi, I'm Dino");
    • b2.setToolTipText("I'm a bird,I'm duck.");
    • b1.setIcon(new ImageIcon("c:udiino.gif"));
    • b1.setContentAreaFilled(false);
    • b1.setBorder(null);
    b2.setIcon(new ImageIcon("c:udiuck.gif")); b2.setContentAreaFilled(false); b2.setBorder(null); b3.setIcon(new ImageIcon("c:udiruck.gif")); b3.setContentAreaFilled(false);
  • 19. Working with Text
  • 20. Class Hierarchy javax.swing.text.JTextComponent javax.swing.JTextField javax.swing.JPasswordField javax.swing.JTextArea javax.swing.JEditorPane javax.swing.JTextPane javax.swing.JComponent
  • 21. javax.swing.text.JTextComponent
    • An abstract class, defines the basic behavior of every text-based swing component.
    • Properties :
    • document
    • A reference to the Document model for the component.
    • This is where the component’s data is stored.
    • default value : null
    • highlighter
    • Type : javax.swing.text.Highlighter
    • default value : null
    • It’s used to refer an object that’s responsible for making highlights in the text.
  • 22. Events
    • CaretEvent
    • Every JTextComponent fires this event every time the component’s caret state changes.
    • Exception : when the text is being selected using mouse.
    • PropertyChangeEvent
    • caret, caretColor, disabledTextColor, document, editable, focusAccelerator, highlighter, keymap, margin, selectedTextColor, and selectionColor.
  • 23. Handling Caret Event
    • jta = new JTextArea(10,15);
    • cp = new JLabel();
    • add(new JScrollPane(jta));
    • add(cp);
    • jta.addCaretListener(this);
    • public void caretUpdate(CaretEvent event)
    • {
    • cp.setText("Cursor Position : "+jta.getCaretPosition());
    • }
  • 24. javax.swing.JTextField
    • Allows user to enter single line of text.
    • ActionEvent is fired when enter key is pressed.
    • Improvements over java.awt.TextField :
    • Allows simple alignment of text (Center, Left, Right).
    • Allows text filtering
    • Events :
    • JTextField objects fire ActionEvent s any time the enter key is pressed.
    • A JTextField fires a PropertyChangeEvent whenever the horizontal Alignment property is updated.
  • 25. Aligning the Text
    • center.setHorizontalAlignment( JTextField.CENTER );
    • right.setHorizontalAlignment( JTextField.RIGHT );
    • left.setHorizontalAlignment( JTextField.LEFT );
  • 26. Interface javax.swing.text.Document
    • Properties :
    • Element defaultRootElement
    • provides access to the Element at the root of the default Element structure hierarchy.
    • Element[] rootElements
    • specifies an array of all root elements (including the default) available in
    • the Document.
    • Position endPosition()
    • Position startPosition()
    • Always refer to the beginning and end of the document, regardless of changes made to it throughout its lifetime.
    • int length
    • Specifies the total number of characters in the Document.
  • 27. Interface javax.swing.text.Element
    • Used to describe an arbitrary portion of a document.
    • Elements do not actually contain a portion of the document, they just define a way of structuring it.
    • Each Element is described by an AttributeSet,
    • Elements may contain other Elements.
  • 28. Element contd.
    • Properties :
    • Document document
    • AttributeSet attributes
    • Element element // indexed
    • int elementCount()
    • int endOffset
    • int startOffset
    • specify the offsets from the beginning of the document that the Element covers. These values change as data is added to or before the Element.
    • boolean leaf
    • indicates whether or not this is a leaf Element
  • 29. Document Hierarchy java.lang.Object javax.swing.text.AbstractDocument javax.swing.text.PlainDocument javax.swing.text.Document java.io.Serializable StyledDocument javax.swing.text.DefaultStyledDocument
  • 30. Manipulating the content of the Document
    • String getText(int offset,int length) throws BadLocationException
    • void insertString(int offset, String str, AttributeSet a) throws BadLocationException
    • void remove(int offs, int len) throws BadLocationException
    • The Document should update its Element structures to reflect the change.
    • void putProperty(Object key, Object value)
    • Object getProperty(Object key)
    • used to store things such as the document title, author, etc.
  • 31. Filtering TextField
    • Alternatives : 2
    • Either Use KeyListener
    • or Modify Document Model
    • jf = new JTextField(20);
    • jf.setDocument(new FixedLength());
    • class FixedLength extends PlainDocument
    • {
    • public void insertString(int offset,String s,AttributeSet a)
    • {
    • if( getLength()+s.length() >10)
    • Toolkit.getDefaultToolkit().beep();
    • else
    • try{ super.insertString(offset,s,a); }catch(Exception e){}
    • }
    • }
    • Benefit over keyListener :
    • any insertion into the Document (including keyboard entry,pasting from the clipboard, or programmatic insertions) will be checked.
  • 32. Listening to Document Events
  • 33. Listening to Document Events
    • jTextArea1.getDocument().addDocumentListener(this);
    • jTextArea1.getDocument().addUndoableEditListener(this);
    • public void changedUpdate(DocumentEvent event)
    • {
    • showDocEvent(event);
    • }
    • public void removeUpdate(DocumentEvent event)
    • {
    • showDocEvent(event);
    • }
    • public void insertUpdate(DocumentEvent event)
    • {
    • showDocEvent(event);
    • }
    • public void undoableEditHappened(UndoableEditEvent event)
    • {
    • jTextArea2.append(event.getEdit().getPresentationName().toString());
    • }
  • 34. Listening to Document Events
    • private void showDocEvent(DocumentEvent event)
    • {
    • jTextArea2.append(" "+event.getType().toString());
    • jTextArea2.append(" Offset : "+event.getOffset()+" length : "+event.getLength());
    • Element e = jTextArea1.getDocument().getDefaultRootElement();
    • DocumentEvent.ElementChange change = event.getChange(e);
    • if(change==null)
    • jTextArea2.append(&quot;<NO ELEMENT CHANGES>&quot;);
    • else
    • {
    • jTextArea2.append(&quot; Changes {Index/Add/Remove} : &quot;+change.getIndex());
    • jTextArea2.append(&quot;/&quot;+change.getChildrenAdded().length);
    • jTextArea2.append(&quot;/&quot;+change.getChildrenRemoved().length);
    • }
    • jTextArea2.append(&quot; &quot;);
    • }
  • 35. javax.swing.event.DocumentListener
    • changedUpdate(DocumentEvent event)
    • Indicates that an attribute or set of attributes in the Document has changed.
    • The range given in the event reflects the offset and length of the affected text.
    • insertUpdate(DocumentEvent event)
    • Indicates that text has been inserted into the Document.
    • The range given in the event reflects the offset and length of the new text.
    • removeUpdate(DocumentEvent event)
    • Indicates that text has been removed from the Document.
    • The range given by the event reflects the offset and length of the removed text, relative to the state of the Document before the text was removed.
  • 36. Working with Elements
  • 37. Working with Elements
    • Handling Caret Event
    • jTextArea2.setText(&quot;Lines : &quot;+jTextArea1.getDocument().getDefaultRootElement().getElementCount()+&quot; Chars : &quot;+jTextArea1.getDocument().getLength() );
    • jTextArea3.setText(&quot;&quot;);
    • int elements = jTextArea1.getDocument().getDefaultRootElement().getElementCount();
    • for( int index=0; index<elements; index++ )
    • {
    • javax.swing.text.Element ee = jTextArea1.getDocument().getDefaultRootElement().getElement(index);
    • int chars = ee.getEndOffset() - ee.getStartOffset();
    • jTextArea3.append(&quot;Line no. &quot;+(index+1)+&quot; has &quot;+chars+&quot; chars. &quot; );
    • }
  • 38. Building a Primitive Browser
  • 39. Building a Primitive Browser
    • Set the MIME Type
    • jEditorPane1.setContentType(&quot;text/html&quot;);
    • jEditorPane1.setEditable(false);
    • On Button Click
    • String path = jTextField1.getText();
    • try{
    • FileInputStream fis = new FileInputStream(path);
    • byte b[] = new byte[(int)fis.getChannel().size()];
    • fis.read(b);
    • jEditorPane1.setText(new String(b));
    • }
    • catch(FileNotFoundException fnfe)
    • {
    • jEditorPane1.setText(&quot;File Location Incorrect&quot;);
    • }
    • catch(IOException e)
    • {
    • jEditorPane1.setText(e.getMessage());
    • }
    • jEditorPane1.getCaret().moveDot(0);
    On FocusEvent on JEditorPane jEditorPane1.getCaret().setVisible(false);
  • 40. Following the Link
  • 41. Following the Link
    • Use javax.swing.event.HyperlinkListener.
    • if( evt.getEventType() == HyperlinkEvent.EventType.ACTIVATED )
    • {
    • try{
    • jEditorPane1.setPage(evt.getURL());
    • jTextField1.setText(evt.getURL().toExternalForm());
    • }
    • catch(IOException ioe)
    • {
    • jEditorPane1.setText(ioe.getMessage());
    • }
    • }
    • else if( evt.getEventType()==HyperlinkEvent.EventType.ENTERED)
    • {
    • jEditorPane1.setToolTipText(&quot;Click to view this page&quot;);
    • }
  • 42.  
  • 43.