User Tools

Site Tools


swing:text_fields

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
swing:text_fields [2018/03/23 14:39] – [Παράδειγμα 1ο] gthanosswing:text_fields [Unknown date] (current) – external edit (Unknown date) 127.0.0.1
Line 1: Line 1:
-====== Text FieldsText Areas & Scroll Panes (Scroll Bars) ======+====== Text Fields Text Areas ======
  
 <WRAP info 70% round center> <WRAP info 70% round center>
Line 106: Line 106:
 </code> </code>
  
-===== Scroll Panes (Scroll Bars) =====+===== Η κλάση Document =====
  
-Όταν ορίζετε ένα text area ορίζετε ένα ελάχιστο εύρος γραμμών και στηλών στις οποίες εκτείνεται το συγκεκριμένο text area, π.χ+Τόσο τα **TextFields** όσο και τα **TextAreas** περιέχουν ένα αντικείμενο της κλάσης [[https://docs.oracle.com/javase/8/docs/api/javax/swing/text/Document.html|Document]]. Η κλάση **Document** διαχειρίζεται το περιεχόμενο κείμενο όλων των κλάσεων αυτού του τύπου και μπορεί να σας επιστρέψει όλο ή μέρος από το περιεχόμενο του //component//. Ένα από τα βασικά χαρακτηριστικά του **Document** είναι ότι σε κάθε μεταβολή του περιεχομένου παράγει //events// του τύπου [[https://docs.oracle.com/javase/8/docs/api/javax/swing/event/DocumentEvent.html|DocumentEvent]], τα οποία μπορείτε να ιάσετε" μέσω ενός αντικειμένου τύπου [[https://docs.oracle.com/javase/8/docs/api/javax/swing/event/DocumentListener.html|DocumentListener]] (//interface//). 
 + 
 +Οι μέθοδοι του interface [[http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html|javax.swing.event.DocumentListener]] δίνονται παρακάτω.
 <code java> <code java>
-JTextArea textArea = new JTextArea(NUMBER_OF_ROWS, NUMBER_OF_CHAR);+//Gives notification that an attribute or set of attributes changed. 
 +void changedUpdate(DocumentEvent e); 
 +//Gives notification that there was an insert into the document. 
 +void insertUpdate(DocumentEvent e); 
 +//Gives notification that a portion of the document has been removed. 
 +void removeUpdate(DocumentEvent e);
 </code> </code>
-Ο χρήστης μπορεί να εισάγει κείμενο που εκτείνεται έξω από τα παραπάνω όρια. Εάν δεν έχετε ορίσει την ιδιότητα της αναδίπλωσης γραμμών στο text area, το κείμενο που βρίσκεται εκτός των παραπάνω ορίων μπορεί να φανεί μόνο αν ορίσετε  scroll bars, ώστε να μπορείτε να πλοηγήστε οριζόντια και κατακόρυφα έξω από τα παραπάνω όρια.  
  
-Scroll bars ορίζονται από το component [[http://docs.oracle.com/javase/7/docs/api/javax/swing/JScrollPane.html|javax.swing.JScrollPane]]. Μπορείτε να φανταστείτε τα scroll bars σαν ένα κινούμενο παράθυρο πάνω από το συνολικό κείμενο που περιέχεται στο text area ή σε οποιοδήποτε άλλο componentΚάθε φορά που μετακινείτε ένα scroll bar μετακινείτε το παράθυρο ορατότητας πάνω από το component. Στην πραγματικότητα ένα text area με scroll bars είναι ένα παράθυρο ορατότητας (JScrollPaneπάνω από το text area, όπως φαίνεται στο παρακάτω σχήμα, όπου το παράθυρο ορατότητας αναφέρεται ως //View port//.+Μπορείτε να δείτε το παρακάτω παράδειγμα χρήσης [[http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html|DocumentEventListeners]] από το [[https://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html|site της Oracle]] (παραλλαγμένο ελαφρά).
  
-{{ :swing:jscrollpane.png |}}+<code java DocumentEventDemo.java> 
 +import javax.swing.*; 
 +import javax.swing.text.*; 
 +import javax.swing.event.*;
  
-Για να ορίσετε ένα text area μέσα σε ένα JScrollPane απαιτείται μία δήλωση της μορφής +import java.awt.Dimension; 
-<code java> +import java.awt.BorderLayout; 
-JScrollPane scolledTextArea = new JScrollPane(textArea)+import java.awt.GridBagLayout
-</code>+import java.awt.GridBagConstraints;
  
-Σε κάθε JScrollPane object ορίζεται την συμπεριφορά του οριζόντιου ScrollBar από την παρακάτω μέθοδο οι οποία λαμβάνει ως ορίσματα τις τιμές που ακολουθούν. +import java.awt.event.*;
-<code java+
-public void setHorizontalScrollBarPolicy(int policy) +
  
-// επιτρεπόμενες τιμές +public class DocumentEventDemo extends JPanel  
-JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS +                               implements ActionListener { 
-JScrollPane.HORIZONTAL_SCROLLBAR_NEVER +    JTextField textField; 
-JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED +    JTextArea textArea; 
-</code>+    JTextArea displayArea;
  
-Αντίστοιχα για το κάθετο ScrollBar  +    public DocumentEventDemo() { 
-<code java> +        super(new GridBagLayout()); 
-public void setVerticalScrollBarPolicy(int policy+        GridBagLayout gridbag = (GridBagLayout)getLayout(); 
 +        GridBagConstraints c = new GridBagConstraints();
  
-// επιτρεπόμενες τιμές +        JButton button = new JButton("Clear"); 
-JScrollPane.VERTICAL_SCROLLBAR_ALWAYS +        button.addActionListener(this);
-JScrollPane.VERTICAL_SCROLLBAR_NEVER +
-JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED +
-</code>+
  
-===== Παραδείγματα =====+        textField new JTextField(20); 
 +        textField.addActionListener(new MyTextActionListener()); 
 +        textField.getDocument().addDocumentListener(new MyDocumentListener()); 
 +        textField.getDocument().putProperty("name", "Text Field");
  
-==== Παράδειγμα 1ο ====+        textArea new JTextArea(); 
 +        textArea.getDocument().addDocumentListener(new MyDocumentListener()); 
 +        textArea.getDocument().putProperty("name", "Text Area"); 
 +        textArea.setLineWrap(true);
  
-Ένα παράδειγμα χρήστης των παραπάνω components δίνεται παρακάτω: +        JScrollPane scrollPane = new JScrollPane(textArea); 
-<code java TextComponentsDemo.java> +        scrollPane.setPreferredSize(new Dimension(200, 75))
-import java.awt.*+        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)
-import java.awt.event.*+        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
-import javax.swing.*;+
  
-public class TextComponentsDemo {+        displayArea = new JTextArea(); 
 +        displayArea.setEditable(false); 
 +        JScrollPane displayScrollPane = new JScrollPane(displayArea); 
 +        displayScrollPane.setPreferredSize(new Dimension(200, 75));
  
-  JFrame frame+        c.gridx = 0
-  JTextField textField; +        c.gridy 0
-  JPasswordField passwdField; +        c.weightx = 1.0
-  JLabel msgLabel; +        c.fill GridBagConstraints.HORIZONTAL
-  JTextArea textArea; +        gridbag.setConstraints(textFieldc); 
-  JCheckBox textFieldCheck, passwdFieldCheck; +        add(textField); 
-   + 
-  public TextComponentsDemo() { +        c.gridx 0
-    frame new JFrame("Text Components Demo")+        c.gridy = 1
-    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)+        c.weightx 0.0
-    JPanel framePanel new JPanel()+        c.gridheight = 2; 
-    framePanel.setLayout(new BoxLayout(framePanelBoxLayout.Y_AXIS)); +        c.fill = GridBagConstraints.BOTH
-    frame.setContentPane(framePanel); +        gridbag.setConstraints(scrollPane, c); 
-    JPanel textFieldPanel new JPanel(new GridLayout(3,3))+        add(scrollPane); 
-    framePanel.add(textFieldPanel)+ 
-    textField new JTextField(15)+        c.gridx = 1
-    textField.addActionListener( new ActionListener() { +        c.gridy 0
-      public void actionPerformed(ActionEvent e) { +        c.weightx = 1.0; 
-        textArea.setText(textArea.getText()+(textArea.getText().isEmpty()?"":"\n")+textField.getText())+        c.weighty 1.0
-        textField.setText(""); +        gridbag.setConstraints(displayScrollPane, c); 
-      } +        add(displayScrollPane); 
-    }); + 
-    textFieldPanel.add(new JLabel("JTextField:")); +        c.gridx = 1
-    textFieldPanel.add(textField)+        c.gridy 2
-    textFieldCheck new JCheckBox("Editable", true)+        c.weightx = 0.0
-    textFieldCheck.addItemListener(new ItemListener() { +        c.gridheight 1
-      public void itemStateChanged(ItemEvent e) { +        c.weighty = 0.0; 
-        if(e.getStateChange() == ItemEvent.SELECTED) +        c.fill GridBagConstraints.HORIZONTAL
-          textField.setEditable(true)+        gridbag.setConstraints(button, c); 
-        else +        add(button); 
-          textField.setEditable(false); + 
-      } +        setPreferredSize(new Dimension(450250)); 
-    }); +        setBorder(BorderFactory.createEmptyBorder(20,20,20,20))
-    textFieldPanel.add(textFieldCheck); +    
-     + 
-    textFieldPanel.add(new JLabel("JPasswordField:"))+    class MyDocumentListener implements DocumentListener 
-    passwdField new JPasswordField()+         
-    textFieldPanel.add(passwdField)+        public void insertUpdate(DocumentEvent e) { 
-    passwdFieldCheck new JCheckBox("Editable", true)+            updateLog(e, "+"); 
-    passwdFieldCheck.addItemListener(new ItemListener() { +        } 
-      public void itemStateChanged(ItemEvent e) { +        public void removeUpdate(DocumentEvent e{ 
-        if(e.getStateChange() == ItemEvent.SELECTED) +            updateLog(e, "-"); 
-          passwdField.setEditable(true)+        } 
-        else +        public void changedUpdate(DocumentEvent e) { 
-          passwdField.setEditable(false); +            //Plain text components don't fire these events.
-      } +
-    }); +
-    textFieldPanel.add(passwdFieldCheck); +
-     +
-    msgLabel = new JLabel("TextArea Options:"JLabel.LEFT);     +
-    textFieldPanel.add(msgLabel); +
-     +
-    String []font = {"Arial""Courier""Verdana""Tahoma"}+
-    JComboBox<String> fontCombo = new JComboBox<>(font); +
-    fontCombo.addActionListener( new ActionListener() +
-      public void actionPerformed(ActionEvent e) { +
-        String option = font[fontCombo.getSelectedIndex()]+
-        textArea.setFont(new Font(option, Font.ITALIC|Font.BOLD, 15)); +
-      +
-    }); +
-     +
-     +
-    String []fontColor = { "RED", "BLUE", "CYAN", "DARK_GRAY" }; +
-    JComboBox<String> fontColorCombo = new JComboBox<>(fontColor); +
-    fontColorCombo.addActionListener( new ActionListener() { +
-      public void actionPerformed(ActionEvent e) { +
-        Color c; +
-        switch(fontColorCombo.getSelectedIndex()) { +
-          case 0: +
-            c = Color.RED; +
-            break; +
-          case 1: +
-            c = Color.BLUE; +
-            break; +
-          case 2: +
-            c = Color.CYAN; +
-            break; +
-          case 3: +
-            c = Color.DARK_GRAY; +
-            break;           +
-          default: +
-            c = Color.YELLOW;+
         }         }
-        textArea.setForeground(c); 
-      } 
-    }); 
-    textFieldPanel.add(fontCombo); 
-    textFieldPanel.add(fontColorCombo); 
-     
-    textArea = new JTextArea(10, 20); 
-    //textArea.setText(""); 
-    textArea.setFont(new Font("Arial", Font.ITALIC|Font.BOLD, 15)); 
-    textArea.setForeground(new Color(250, 30, 30)); 
-    framePanel.add(textArea); 
-     
-    frame.pack(); 
-    frame.setVisible(true); 
-  } 
-   
-  public static void main(String []args) { 
-    javax.swing.SwingUtilities.invokeLater( new Runnable() { 
-      public void run() { 
-        new TextComponentsDemo(); 
-      } 
-    }); 
-  } 
-} 
-</code> 
  
-<WRAP tip 80% center round> +        public void updateLog(DocumentEvent e, String action) { 
-Παρατηρήστε ότι μπορείτε να χρησιμοποιήσετε έναν [[https://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionListener.html|ActionListener]] πάνω σε ένα [[https://docs.oracle.com/javase/8/docs/api/javax/swing/JTextField.html|JTextField]]. Το [[https://docs.oracle.com/javase/8/docs/api/java/awt/event/ActionEvent.html|ActionEvent]] που παράγεται συμβαίνει όταν ο χρήστης πατήσει το πλήκτρο //Enter// από το πληκτρολόγιο (δεν συνδέεται με τη λειτουργία του ποντικιού). +            Document doc = (Document)e.getDocument(); 
-</WRAP> +            int changeLength = e.getLength(); 
-  +            displayArea.append( 
-==== Παράδειγμα 2ο ====+                "["+doc.getProperty("name")+"" +  
 +                action + changeLength + " character" +  
 +                ((changeLength == 1) ? "\n" "s\n") + 
 +                "  Text length = " + doc.getLength() + "\n"); 
 +            displayArea.setCaretPosition(displayArea.getDocument().getLength()); 
 +        } 
 +    }
  
-Το 2ο παράδειγμα είναι από το βιβλίο του Savitch.  +    class MyTextActionListener implements ActionListener { 
-<code java ScrollBarDemo.java> +        /** Handle the text field Return. */ 
-import javax.swing.*; +        public void actionPerformed(ActionEvent e) { 
-import java.awt.*+            int selStart = textArea.getSelectionStart()
-import java.awt.event.*;+            int selEnd = textArea.getSelectionEnd();
  
-public class ScrollBarDemo extends JFrame implements ActionListener { +            textArea.replaceRange(textField.getText(), 
-  public static final int WIDTH = 600+                                  selStart, selEnd)
-  public static final int HEIGHT = 400+            textField.selectAll()
-  public static final int LINES = 15; +        } 
-  public static final int CHAR_PER_LINE = 30; +    }
-  private JTextArea memoDisplay; +
-  private String memo1; +
-  private String memo2;+
  
-  public static void main(String[] args)  { +    /** Handle button click. */ 
-    ScrollBarDemo gui = new ScrollBarDemo(); +    public void actionPerformed(ActionEvent e) { 
-    gui.setVisible(true); +        displayArea.setText(""); 
-  } +        textField.requestFocus(); 
-   +    }
-  public ScrollBarDemo() { +
-    super("Scroll Bars Demo"); +
-    setSize(WIDTH, HEIGHT); +
-    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); +
-    JPanel buttonPanel = new JPanel(); +
-    buttonPanel.setBackground(Color.LIGHT_GRAY); +
-    buttonPanel.setLayout(new FlowLayout()); +
-    JButton memo1Button = new JButton("Save Memo 1"); +
-    memo1Button.addActionListener(this); +
-    buttonPanel.add(memo1Button); +
-    JButton memo2Button = new JButton("Save Memo 2"); +
-    memo2Button.addActionListener(this); +
-    buttonPanel.add(memo2Button); +
-    JButton clearButton = new JButton("Clear"); +
-    clearButton.addActionListener(this); +
-    buttonPanel.add(clearButton); +
-    JButton get1Button = new JButton("Get Memo 1"); +
-    get1Button.addActionListener(this); +
-    buttonPanel.add(get1Button); +
-    JButton get2Button = new JButton("Get Memo 2"); +
-    get2Button.addActionListener(this); +
-    buttonPanel.add(get2Button); +
-    add(buttonPanel, BorderLayout.SOUTH); +
-    JPanel textPanel = new JPanel(); +
-    textPanel.setBackground(Color.BLUE);+
  
-    memoDisplay = new JTextArea(LINES, CHAR_PER_LINE); +    /** 
-    memoDisplay.setBackground(Color.WHITE); +     * Create the GUI and show it For thread safety, 
-    JScrollPane scrolledText = new JScrollPane(memoDisplay); +     * this method should be invoked from the 
-    scrolledText.setHorizontalScrollBarPolicy( +     * event-dispatching thread
-    JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); +     */ 
-    scrolledText.setVerticalScrollBarPolicy( +    private static void createAndShowGUI() { 
-    JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); +        //Create and set up the window
-    textPanel.add(scrolledText); +        JFrame frame new JFrame("DocumentEventDemo"); 
-    add(textPanel, BorderLayout.CENTER); +        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
-  } +
-   +
-  public void actionPerformed(ActionEvent e) { +
-    String actionCommand = e.getActionCommand(); +
-    if (actionCommand.equals("Save Memo 1")) +
-      memo1 memoDisplay.getText(); +
-    else if (actionCommand.equals("Save Memo 2")) +
-      memo2 = memoDisplay.getText(); +
-    else if (actionCommand.equals("Clear")) +
-      memoDisplay.setText(""); +
-    else if (actionCommand.equals("Get Memo 1")) +
-      memoDisplay.setText(memo1); +
-    else if (actionCommand.equals("Get Memo 2")) +
-      memoDisplay.setText(memo2); +
-    else +
-      memoDisplay.setText("Error in memo interface"); +
-  } +
-   +
-+
-</code>+
  
-===== Document Listeners =====+        //Create and set up the content pane. 
 +        JComponent newContentPane new DocumentEventDemo(); 
 +        newContentPane.setOpaque(true); //content panes must be opaque 
 +        frame.setContentPane(newContentPane);
  
-Κάθε component ή κάθε κατηγορία component συνδέεται με κάποιο Listener Interface. Τα παραπάνω text related components συνδέονται με το interface [[http://docs.oracle.com/javase/7/docs/api/javax/swing/event/DocumentListener.html|javax.swing.event.DocumentListener]]. Οι μέθοδοι του συγκεκριμένου interface δίνονται παρακάτω. +        //Display the window. 
-<code java> +        frame.pack(); 
-void changedUpdate(DocumentEvent e); +        frame.setVisible(true); 
-//Gives notification that an attribute or set of attributes changed.+    }
  
-void insertUpdate(DocumentEvent e); +    public static void main(String[] args{ 
-//Gives notification that there was an insert into the document.+        //Schedule a job for the event-dispatching thread: 
 +        //creating and showing this application's GUI. 
 +        javax.swing.SwingUtilities.invokeLater(new Runnable() { 
 +            public void run() { 
 +                createAndShowGUI(); 
 +            } 
 +        }); 
 +    } 
 +}
  
-void removeUpdate(DocumentEvent e); 
-//Gives notification that a portion of the document has been removed. 
 </code> </code>
  
 +| Προηγούμενο: [[:swing:buttons | Buttons, CheckBoxes & RadioButtons ]] | [[:toc | Περιεχόμενα ]] | Επόμενο: [[:swing:jscrollpane | Η κλάση JScrollPane ]] |
  
swing/text_fields.1521815994.txt.gz · Last modified: 2018/03/23 14:39 by gthanos