Docstoc

Exemplu - Facultatea de Automati

Document Sample
Exemplu - Facultatea de Automati Powered By Docstoc
					                                                           Laborator 6

1. Exemplu Swing: JOptionPane
Pentru a crea dialoguri standard simple se poate folosi clasa JOptionPane:

import javax.swing.*;
       class JOptionPaneDemo {
              JOptionPane optionPane;
              void launchFrame() {
                     optionPane = new JOptionPane();
                     String name = optionPane.showInputDialog("Hi, what’s your name?");
                     optionPane.showMessageDialog(null, "Nice to meet you, " + name +
              ".", "Greeting...",optionPane.PLAIN_MESSAGE);
                       System.exit(0);
              }
               public static void main(String args[]) {
                     new JOptionPaneDemo().launchFrame();
                     }
                       }



2. Exemplu: JToggleButton

Clasa JToggleButton este clasa parinte a celor 2 clase JCheckBox si JRadioButton. Aceasta clasa nu are echivalent
in AWT.

public class ToggleButtonPanel extends JPanel {
  public ToggleButtonPanel() {
    // Set the layout to a GridLayout
    setLayout(new GridLayout(4,1, 10, 10));
    add (new JToggleButton ("Fe"));
    add (new JToggleButton ("Fi"));
    add (new JToggleButton ("Fo"));
    add (new JToggleButton ("Fum"));
  }
}



3. Exemplu: JScrollBar

JScrollBar este o versiune swing a componentei java.awt.Scrollbar.

Constructorii clasei JScrollBar

       JScrollBar() creeaza o instanta a clasei JScrollBar.
       JScrollBar(int orientation, int value, int extent, int minimum, int maximum ) creeaza o instanta a clasei
        JScrollBar cu o orientare specificata (HORIZONTAL or VERTICAL) si atribuie valorile minime, maxime
        si curente.

public class ScrollbarPanel extends JPanel {

  public ScrollbarPanel() {
    setLayout(new BorderLayout());
    JScrollBar scrollBar1 = new JScrollBar (
      JScrollBar.VERTICAL, 0, 5, 0, 100);
        add(scrollBar1, BorderLayout.EAST);
        JScrollBar scrollBar2 = new JScrollBar (
          JScrollBar.HORIZONTAL, 0, 5, 0, 100);
        add(scrollBar2, BorderLayout.SOUTH);
    }
}




4. Exemplu: JTabbedPane

Componenta JTabbedPane ofera mai multe taburi pentru a accesa rapid mai multe panouri (panels).

public class TabbedPanel extends JPanel {
  String tabs[] = {"One", "Two", "Three", "Four"};
  public JTabbedPane tabbedPane = new JTabbedPane();
  public TabbedPanel() {
    setLayout (new BorderLayout());
    for (int i=0;i<tabs.length;i++)
      tabbedPane.addTab (tabs[i], null, createPane (tabs[i]));
    tabbedPane.setSelectedIndex(0);
    add (tabbedPane, BorderLayout.CENTER);
  }
  JPanel createPane(String s) {
    JPanel p = new JPanel();
    p.add(new JLabel(s));
    return p;
  }
}


5. Exemplu: JTable
Folosind componenta JTable se pot afisa date sub forma tabelara, optional putandu-se si edita datele din table.
JTable nu stocheaza datele; este doar o modalitate de afisare a datelor.

        1. Crearea tabelului

String[] columnNames = {"First Name",
                         "Last Name",
                         "Sport",
                         "# of Years",
                         "Vegetarian"};
//fiecare coloana poate contine orice tip de data
Object[][] data = {
    {"Mary", "Campione",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", "Milne",
     "Pool", new Integer(10), new Boolean(false)}
};
//adaugarea datelor in tabel
JTable table = new JTable(data, columnNames);

2 dintre constructorii clasei JTable care accepta direct date sunt:
        JTable(Object[][] rowData, Object[] columnNames)
        JTable(Vector rowData, Vector columnNames)

Avantajul acestor constructori este usurinta cu care se pot folosi. Totusi ei au cateva dezavantaje:

        Automat creeaza fiecare celula editabila.
        Trateaza toate tipurile de date ca stringuri. De exemplu daca se foloseste unul din constructorii de mai sus,
         datele de tip Boolean vor fi afisate ca string
        Datele pe care le puneti in tabel trebuie sa provina din vectori sau array, ceea ce nu este convenabil pentru
         anumite date, de exemplu pentru cele selectate dintr-o baza de date care vor trebui copiate intr-un vector.

2. Adaugarea tabelului la container

Este usor sa se adauge tabelul intr-un scroll pane.
           JScrollPane scrollPane = new JScrollPane(table);
           table.setPreferredScrollableViewportSize(new Dimension(500, 70));

Scroll pane-ul automat afiseaza capatul de table, chiar daca scrolul este jos.

Daca se nu se foloseste un scroll pane, atunci trebuie adaugat separate capatul de table: De exemplu:

           container.setLayout(new BorderLayout());
           container.add(table.getTableHeader(), BorderLayout.PAGE_START);
           container.add(table, BorderLayout.CENTER);

3. Redimensionearea coloanelor

-Se foloseste metoda setPreferredWidth pentru fiecare coloana a tabelei.

         TableColumn column = null;
         for (int i = 0; i < 5; i++) {
             column = table.getColumnModel().getColumn(i);
             if (i == 2) {
                 column.setPreferredWidth(100); //sport column is bigger
             } else {
                 column.setPreferredWidth(50);
             }
         }

4. Detectarea selectiilor utilizatorului

Urmatorul exemplu demonstreaza cum se poate detecta daca un utilizator a seletat un rand dintr-o tabela. Implicit,
intr-o tabela se pot selecta mai multe randuri.
Folosind metoda setSelectionMode se poate seta ca doar un rand sa fie selectat la un moment dat:

table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
...
//Ask to be notified of selection changes.
ListSelectionModel rowSM = table.getSelectionModel();
rowSM.addListSelectionListener(new ListSelectionListener() {
    public void valueChanged(ListSelectionEvent e) {
        //Ignore extra messages.
        if (e.getValueIsAdjusting()) return;

            ListSelectionModel lsm =
                  (ListSelectionModel)e.getSource();
              if (lsm.isSelectionEmpty()) {
                  ...//no rows are selected
              } else {
                  int selectedRow = lsm.getMinSelectionIndex();
                  ...//selectedRow is selected
              }
      }
});

Exemplu:
import    javax.swing.*;
import    javax.swing.event.*;
import    java.awt.*;
import    java.awt.event.*;
public    class SimpleTable extends JPanel{

          String[] columnNames = {"First Name",
               "Last Name",
               "Sport",
               "# of Years",
               "Vegetarian"};
          //fiecare coloana poate contine orice tip de data
          Object[][] data = {
          {"Mary", "Campione",
          "Snowboarding", new Integer(5), new Boolean(false)},
          {"Alison", "Huml",
          "Rowing", new Integer(3), new Boolean(true)},
          {"Kathy", "Walrath",
          "Knitting", new Integer(2), new Boolean(false)},
          {"Sharon", "Zakhour",
          "Speed reading", new Integer(20), new Boolean(true)},
          {"Philip", "Milne",
          "Pool", new Integer(10), new Boolean(false)}
          };
          public SimpleTable(){

          JTable tbl = new JTable(data, columnNames);
          JScrollPane sp = new JScrollPane(tbl);
          tbl.setPreferredScrollableViewportSize(new Dimension(500,70));
          tbl.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
          ListSelectionModel rowSM = tbl.getSelectionModel();
          rowSM.addListSelectionListener(new ListSelectionListener() {
          public void valueChanged(ListSelectionEvent e) {
              //Ignore extra messages.
              if (e.getValueIsAdjusting()) return;

               ListSelectionModel lsm =
                   (ListSelectionModel)e.getSource();
               if (lsm.isSelectionEmpty()) {
                 System.out.println("No selection");
               } else {
                   int selectedRow = lsm.getMaxSelectionIndex();
                   System.out.println(selectedRow);
               }
          }
  });


      add(sp);
      }
 public static void main(String args[]){
            JFrame f = new JFrame("sss");

           SimpleTable stbl = new SimpleTable();
           f.getContentPane().add(stbl);
        f.pack();
        f.setVisible(true);
    }

}


Crearea unei tabele pe baza unui model
Tabelele se mai pot crea si prin citirea datelor dintr-un obiect care implementeaza interfata TableModel:

Diferentele dintre tabelul acesta si tabelul de mai sus sunt:

           Datale din table pot fi afisate in orice format
           In acest exemplu s-a implementat o tabela care nu permite editarea numelor coloanelor

public TableDemo() {
    ...
    JTable table = new JTable(new MyTableModel());
    ...
}

class MyTableModel extends AbstractTableModel {
    String[] columnNames = {"First Name",
                         "Last Name",
                         "Sport",
                         "# of Years",
                         "Vegetarian"};
  //fiecare coloana poate contine orice tip de data
   Object[][] data = {
    {"Mary", "Campione",
     "Snowboarding", new Integer(5), new Boolean(false)},
    {"Alison", "Huml",
     "Rowing", new Integer(3), new Boolean(true)},
    {"Kathy", "Walrath",
     "Knitting", new Integer(2), new Boolean(false)},
    {"Sharon", "Zakhour",
     "Speed reading", new Integer(20), new Boolean(true)},
    {"Philip", "Milne",
     "Pool", new Integer(10), new Boolean(false)}
};


        public int getColumnCount() {
            return columnNames.length;
        }

        public int getRowCount() {
            return data.length;
        }

        public String getColumnName(int col) {
            return columnNames[col];
        }

        public Object getValueAt(int row, int col) {
            return data[row][col];
     }

     public Class getColumnClass(int c) {
         return getValueAt(0, c).getClass();
     }

     /*
       * Don't need to implement this method unless your table's
       * editable.
       */
     public boolean isCellEditable(int row, int col) {
          //Note that the data/cell address is constant,
          //no matter where the cell appears onscreen.
          if (col < 2) {
              return false;
          } else {
              return true;
          }
     }

     /*
       * Don't need to implement this method unless your table's
       * data can change.
       */
     public void setValueAt(Object value, int row, int col) {
          data[row][col] = value;
          fireTableCellUpdated(row, col);
     }
     ...
}


Detectarea schimbarii datelor din tabel

Pentru a efctuta anumite operatii cand utilizatorul editeaza datele din tabel trebuie inregistrat ascultatorul
TableModelListener pe modelul tabelei:

import javax.swing.event.*;
import javax.swing.table.TableModel;

public class SimpleTableDemo ... implements TableModelListener {
    ...
    public SimpleTableDemo() {
        ...
        table.getModel().addTableModelListener(this);
        ...
    }

     public void tableChanged(TableModelEvent e) {
         int row = e.getFirstRow();
         int column = e.getColumn();
         TableModel model = (TableModel)e.getSource();
         String columnName = model.getColumnName(column);
         Object data = model.getValueAt(row, column);

           ...// Do something with the data...
     }
     ...
}

6.Exemplu: JTree
Cu ajutorul componenetei JTree se pot afisa ierarhii de date.
Fiecare rand afisat de arbore contine exact un element care se numeste nod. Fiecare arbore are o radacina din care
descind alte noduri. Implicit, arborele afiseaza nodul radacina care poate avea sau nu copii.

1.Crearea unui obiect JTree

         private JTree tree;
         ...
         public TreeDemo() {
             ...
           DefaultMutableTreeNode top = new DefaultMutableTreeNode("The
           Java Series");
           createNodes(top);
           tree = new JTree(top);
             ...
           JScrollPane treeView = new JScrollPane(tree);
             ...
         }
         private void createNodes(DefaultMutableTreeNode top) {
             DefaultMutableTreeNode category = null;
             DefaultMutableTreeNode book = null;

             category = new DefaultMutableTreeNode("Books for Java
         Programmers");
             top.add(category);

              //original Tutorial
              book = new DefaultMutableTreeNode(new BookInfo
                  ("The Java Tutorial: A Short Course on the Basics",
                  "tutorial.html"));
              category.add(book);

              //Tutorial Continued
              book = new DefaultMutableTreeNode(new BookInfo
                  ("The Java Tutorial Continued: The Rest of the JDK",
                  "tutorialcont.html"));
              category.add(book);

              //JFC Swing Tutorial
              book = new DefaultMutableTreeNode(new BookInfo
                  ("The JFC Swing Tutorial: A Guide to Constructing GUIs",
                  "swingtutorial.html"));
              category.add(book);

              //...add more books for programmers...

             category = new DefaultMutableTreeNode("Books for Java
         Implementers");
             top.add(category);

              //VM
              book = new DefaultMutableTreeNode(new BookInfo
                   ("The Java Virtual Machine Specification",
                    "vm.html"));
              category.add(book);

              //Language Spec
              book = new DefaultMutableTreeNode(new BookInfo
                  ("The Java Language Specification",
                   "jls.html"));
              category.add(book);
Argumentul constructorului DefaultMutableTreeNode este un obiect care contine datele asociate nodului
arborelui.Acesta poate fi string sau un anumit obiect creat de utilizator. Pentru un obiect creat de utilizator trebuie
implementata motoda toString a.i sa returneze stringul care trebuie afisat pentru nodul respectiv.

Selectarea unui nod
Pentru a raspunde actiunii de selectare a unui nod din ierarhie trebuie implementat un ascultator si
inregistrat pentru arbore.

//Where the tree is initialized:
    tree.getSelectionModel().setSelectionMode
            (TreeSelectionModel.SINGLE_TREE_SELECTION);

     //Listen for when the selection changes.
     tree.addTreeSelectionListener(this);
...
public void valueChanged(TreeSelectionEvent e) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)
                       tree.getLastSelectedPathComponent();

     if (node == null) return;

     Object nodeInfo = node.getUserObject();
     if (node.isLeaf()) {
         BookInfo book = (BookInfo)nodeInfo;
         displayURL(book.bookURL);
     } else {
         displayURL(helpURL);
     }
}

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:11
posted:5/1/2010
language:Romanian
pages:8